I\'m having a hard time implementing Read for a tree structure. I want to take a left-associative string (with parens) like ABC(DE)F
and convert it into a tree.
This very-much looks like a stack structure. When you encounter your input string "ABC(DE)F"
, you Leaf
any atom you find (non-parenthesis) and put it in an accumulator list. When you have 2 items in the list, you Branch
them together. This could be done with something like (note, untested, just including to give an idea):
read' [r,l] str = read' [Branch l r] str
read' acc (c:cs)
-- read the inner parenthesis
| c == '(' = let (result, rest) = read' [] cs
in read' (result : acc) rest
-- close parenthesis, return result, should be singleton
| c == ')' = (acc, cs)
-- otherwise, add a leaf
| otherwise = read' (Leaf c : acc) cs
read' [result] [] = (result, [])
read' _ _ = error "invalid input"
This may require some modification, but I think its enough to get you on the right track.