在Graham Hutton的“在哈斯克尔编程”一书中,解决第10章练习3时出错。
当左侧和右侧树木上的叶子数量不超过1时,这些树木被认为是平衡的。 当然,它本身似乎是平衡的。定义一个函数以确定树是否平衡。 首先,定义一个计算树中叶子数量的函数。
data Tree = Leaf Int | Node Tree Tree
leaves :: Tree -> Int
leaves (Leaf _) = 1 leaves
leaves (Node l r) = leaves l + leaves r
balanced :: Tree -> Bool
(-) :: Int -> Int -> Integer
balanced (Leaf _) = True
balanced (Node l r) = abs (leaves l - leaves r) <= 1
&& balanced l && balanced r
我对Haskell一无所知,但我的教授给了我这个任务。帮助
答案 0 :(得分:0)
您的代码看起来很好,但是您有一些小错误。
leaves :: Tree -> Int
leaves (Leaf _) = 1 -- not 1 leaves
leaves (Node l r) = leaves l + leaves r
balanced :: Tree -> Bool
-- don't declare (-) here, it's already declared by the libraries!
balanced (Leaf _) = True
balanced (Node l r) = abs (leaves l - leaves r) <= 1
&& balanced l && balanced r -- indent this more