【发布时间】:2017-04-04 18:34:10
【问题描述】:
我在 Haskell 中对二叉树的定义如下:
data BTree x = Nil | BNode x (BTree x) (BTree x)
然后我有这个数据类型的折叠定义:
foldB :: (x -> u -> u -> u) -> u -> BTree x -> u
foldB f a Nil = a
foldB f a (BNode x l r) = f x (foldB f a l)(foldB f a r)
所以我希望我可以简单地使这个函数对所有值求和:
sumBFold :: (Num a) => BTree a -> a
sumBFold x = foldB (+) 0 x
但这不起作用,我终其一生都无法弄清楚原因。 我收到的错误消息的有用部分是:
Couldn't match type `a` with `a -> a'
`a' is a rigid type variable bound by the type signature for:
sumBFold :: forall a. Num a => BTree a -> a
Expected type: (a -> a) -> a -> a -> a
Actual type: (a -> a) -> (a -> a) -> a -> a
In the first argument of folB namely `(+)`
【问题讨论】:
-
你需要传递给
foldB的函数需要3个参数,而(+)只需要2个。
标签: haskell binary-tree fold