I apologize for the subject being unclear. I'm doing Haskell 99 as a beginner, and have encountered the concept of monad first time in my life in the solution to 67A. The part of the problem I'm struggling with is to define a function stringToTree
that translates sequences like a(b,c)
to a Tree
: Branch a (Branch b Empty Empty) (Branch c Empty Empty)
.
I have tried several "soft" introductions to monads, and failed like many others. I hope by understanding this solution will finally lead me in-door, so I decided to give it a shot here.
Questions
- Would anyone briefly explain what the function
stringToTree :: (Monad m) => String -> m (Tree Char)
defined in the solution? To make this question self-contained, I copied the code from there
stringToTree :: (Monad m) => String -> m (Tree Char)
stringToTree "" = return Empty
stringToTree [x] = return $ Branch x Empty Empty
stringToTree str = tfs str >>= \ ("", t) -> return t
where tfs a@(x:xs) | x == ',' || x == ')' = return (a, Empty)
tfs (x:y:xs)
| y == ',' || y == ')' = return (y:xs, Branch x Empty Empty)
| y == '(' = do (',':xs', l) <- tfs xs
(')':xs'', r) <- tfs xs'
return $ (xs'', Branch x l r)
tfs _ = fail "bad parse"
- Why is
monad
useful here? I hope to see how monads largely reduce the difficulties, of course only after one understands it, while defining this function.