Haskell:递归数据类型 - 将[String]解析为n-ary树

时间:2014-09-30 09:22:53

标签: parsing haskell tree

我正在尝试将字符串列表解析为n-ary树,定义为:

data Tree = Leaf Int | Node [Tree] deriving (Show)

如果我有[String] = ["(", "1", "(", "2", "3", ")", ")"],我希望将其解析为一个带有一个Leaf(1)的节点和另一个带有其他Leaf(2,3)的嵌套节点的树。

我已经尝试了几天,但我无法理解插入任意数量的孩子。我以前为一个简单的语法编写了一个AST,但后来我已经在数据中定义了多个孩子。

“(Tree,[String])”中的[String]用于跟踪尚未解析的字符串。

data Tree = Leaf Int | Node [Tree] deriving (Show)
tree :: [String] -> (Tree, [String])
tree [] = error "I can't let you do that, Dave"
tree (x:xs) | all isDigit x = (Leaf (read x), xs)
            | -- <- Node?

我真的很感激一些帮助或一些提示让我更进一步。

1 个答案:

答案 0 :(得分:3)

让我们将结果类型从(Tree, [String])更改为[Tree]

我们使用附加参数作为累加器并使用递归:

tree :: [String] -> [Tree]
tree xs = let (Node ts, zs) = treenode (xs ++ ")") [] in ts

treenode :: [String] -> [Tree] -> (Tree, [String])
treenode []       _  = error "I can't let you do that, Dave"
treenode ("(":xs) ts = let (n, xs') = treenode xs [] in treenode xs' (n : ts)
treenode (")":xs) ts = (Node ts, xs)
treenode (x:xs)   ts = treenode xs (Leaf (read x) : ts)