I posted this question on StackOverflow.
Given this algebraic data type:
data Tree a = Node {
rootLabel :: a,
subForest :: [Tree a]
} deriving (Show)
and function:
treeFold :: (a -> [b] -> b) -> Tree a -> b
treeFold f (Node x ts) = f x (map (treeFold' f) ts)
Write a function (using treeFold
) with the signature: Tree a -> [a]
.
Given this example:
ghci> stringTree
Node {rootLabel = "foo",
subForest = [Node {rootLabel = "bar", subForest = []},
Node {rootLabel = "bippy", subForest = []},
Node {rootLabel = "baz", subForest = []} ]}
I came up with:
ghci> treeFold' (\x y -> x : (join y) ) stringTree
["foo","bar","bippy","baz"]
Please review this implementation.
I'm not sure if introducing join
here (from Control.Monad
) is overkill. Note that I don't have a good sense as to whether it's OK to casually use Monads - mainly using the right abstraction - not going overboard.