Implementing `read` for a left-associative tree in Haskell

后端 未结 3 1316
时光说笑
时光说笑 2020-12-30 11:39

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.

3条回答
  •  孤城傲影
    2020-12-30 12:15

    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.

提交回复
热议问题