简体   繁体   English

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

[英]Haskell : Recursive datatype - parse [String] to n-ary tree

I am trying to parse a list of strings into a n-ary tree, defined as: 我试图将字符串列表解析为n-ary树,定义为:

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

If i have the [String] = ["(", "1", "(", "2", "3", ")", ")"] , I want this to be parsed into a tree with a Node with one Leaf (1) and another nested Node with the other Leafs (2, 3). 如果我有[String] = ["(", "1", "(", "2", "3", ")", ")"] ,我希望将其解析为带有Node的树一个Leaf(1)和另一个嵌套Node与其他Leafs(2,3)。

I've been trying for a couple days, but I cannot get my head around inserting an arbitrary number of children. 我已经尝试了几天,但我无法理解插入任意数量的孩子。 I have previously written a AST for a simple grammar, but then I had the number of children already defined in the Data. 我以前为一个简单的语法编写了一个AST,但后来我已经在数据中定义了多个孩子。

the [String] in "(Tree, [String])" is meant to keep track of the strings that have not yet been parsed. “(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?

I would really appreciate some help or some hints to get me a bit further. 我真的很感激一些帮助或一些提示让我更进一步。

Let change a bit resulting type from (Tree, [String]) to [Tree] . 让我们将(Tree, [String])结果类型更改为[Tree]

We use additional argument as accumulator and use recursion: 我们使用额外的参数作为累加器并使用递归:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM