2
\$\begingroup\$

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.

\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

I don't think that using monads here itself is overkill, but I would suggest using concat instead of join.

There are no different Monads that could be an argument to join here. Using concat is more apropriate (imo).

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.