这是一棵二叉树,我正在尝试计算叶子的总和
-1
/ \
-5 10
/ \
-4 30
/ \
13 17
给出了数据声明。
data Tree = TNode Int [ Tree ] | TLeaf Int
这是我的代码
let t = TNode (-1) [TNode (-5) [ TNode (-4) [ Tleaf 13, Tleaf 17] , Tleaf 30 ] ,Tleaf 10 ]
sumLeaves (Tleaf x)= x
sumLeaves (TNode x [tree])= sum[sumLeaves tree]
当我运行程序 sumLeaves t 时,它表明函数 sumLeaves 中存在非穷举模式。我认为问题是程序无法计算,当有一个节点有两个叶子时,但我不知道如何解决它。非常感谢您的帮助。
编辑:test1:
sumLeaves1 (Tleaf x)= [x]
sumLeaves1 (TNode x [Tleaf y])=[y]
sumLeaves1 (TNode x (y:ys))= sum ( (sumLeaves1 y) ++ (sumLeaves1 (TNode x ys)) )
测试2:
sumLeaves (Tleaf x)= x
sumLeaves (TNode x [Tleaf y])=y
sumLeaves (TNode x (y:ys))= (sumLeaves y) + sumLeaves (TNode x ys)
测试 2 工作正常,但测试 1 给出错误,当我删除 sum() 时,它给出了一个列表 [13,17,30,10] ,这是正确的列表,但是 >sum ( [13,17,30, 10])在程序中工作。我该如何克服它?