Fas*_*ger 0 haskell pattern-matching
问题出在标题:)
我的代码:
data tree a = Leaf a | Node (tree a) (tree a)
treeo = Node((Node(Leaf 1)(Node (Leaf 10)(Leaf 11))))
(Node(Leaf 12)(Leaf 13))
-- count all leafs:
lcounter(Leaf a) = 1
lcounter(Node a b)= lcounter a + lcounter b
-- count all nodes?:
Run Code Online (Sandbox Code Playgroud)
首先注意数据类型定义应该从大写开始:
data Tree a = Leaf a | Node (Tree a) (Tree a)
Run Code Online (Sandbox Code Playgroud)
要统计所有节点,它几乎就是你所做的,一个简单的模式匹配树数据构造函数:
countNodes :: Tree a -> Int
countNodes (Leaf a) = 0
countNodes (Node left right) = 1 + countNodes left + countNodes right
Run Code Online (Sandbox Code Playgroud)
用你的例子:
let tree = Node((Node (Leaf 1) (Node (Leaf 10) (Leaf 11))))(Node (Leaf 12) (Leaf 13))
countNodes tree -- 4
Run Code Online (Sandbox Code Playgroud)