我有以下数据类型:
data Tree a = Node [Tree a]
我想计算这样的树中有多少个节点,所以我定义了以下内容:
count:: Tree a -> Integer
count [] = 0
count Node label [childrenTree a] = 1 + count a
这给了我一个错误,说"在模式中解析错误:true"。如果我将childrenTree a
更改为Tree a
则说明数据构造函数不在范围内。
我该如何解决这个问题?
这指定函数count
有三个参数,这不是你想要的:
count Node label [childrenTree a] = ...
-- ^1 ^2 ^3
进一步
count [] = ...
指定存在单个参数,该参数必须是列表(确切地说是空列表(。您希望count
将树作为参数,而不是列表。
编写代码的正确方法是:
count:: Tree a -> Integer
count (Node subtrees) = ... -- here, we have subtrees :: [Tree a]
或者:
count:: Tree a -> Integer
count (Node []) = ...
count (Node (t:ts)) = ...
--here t is the first tree in the list, ts is the list of remaining ones
这是一个完整的工作程序:
data Tree a = Node [Tree a]
count:: Tree a -> Integer
count (Node []) = 1
count (Node (t:ts)) = count t + count (Node ts)
-- a little test
main :: IO ()
main = print (count (Node [Node [], Node [Node[], Node[]]]))
输出是5
,这是输入中的Node
秒数。
在一般树中有一个棘手的部分需要考虑,你在树本身中具有函数,并且您在树列表上有递归。 另一件事是,你的树是这样的,不保存任何有价值的信息,你可以把它改一点,如下:
data Tree a = Node a [Tree a] deriving (Show)
这两个函数将如下所示:
count:: Tree a -> Integer
count (Node _ trees) = 1 + countLs trees
countLs [] = 0
countLs (t:ts) = (count t) + (countLs ts)
还有一个小演示:
genTree1 = NodeG "1" [NodeG "2" [],
NodeG "3" [NodeG "4" [],
NodeG "5" [NodeG "6" [],
NodeG "7" [],
NodeG "8" []
]
]
]
运行示例:
$> count genTree1
8