You can turn on the DeriveFoldable
feature, and let Haskell do the work for you:
{-# LANGUAGE DeriveFoldable #-}
data Tree a = Node (Tree a) a (Tree a) | Empty deriving Foldable
Since you want to use infix notation, we thus swap a
and Tree a
as parameter here.
We can then use the toList
function from Data.Foldable
:
Prelude> import Data.Foldable
Prelude Data.Foldable> toList (Node (Node Empty 1 Empty) 4 (Node (Node Empty 2 Empty) 5 Empty))
[1,4,2,5]
You do not only can convert the tree to a list, but you can use the functions that work on a foldable Foldable
, for example:
Prelude Data.Foldable> sum (Node (Node Empty 4 Empty) 2 (Node Empty 5 Empty))
11
Prelude Data.Foldable> product (Node (Node Empty 4 Empty) 2 (Node Empty 5 Empty))
40
Prelude Data.Foldable> length (Node (Node Empty 4 Empty) 2 (Node Empty 5 Empty))
3
Prelude Data.Foldable> minimum (Node (Node Empty 4 Empty) 2 (Node Empty 5 Empty))
2
Prelude Data.Foldable> maximum (Node (Node Empty 4 Empty) 2 (Node Empty 5 Empty))
5