[英]Binary Tree Fold Functions
I have the definition of a Binary tree in Haskell as the following: 我在Haskell中对二叉树的定义如下:
data BTree x = Nil | BNode x (BTree x) (BTree x)
I then have a fold definition for this data type: 然后,我对此数据类型有一个折叠定义:
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)
So I hoped that I could simply make this function to sum all the values: 所以我希望我可以简单地使此函数求和所有值:
sumBFold :: (Num a) => BTree a -> a
sumBFold x = foldB (+) 0 x
But this does not work, and I cannot for the life of me figure out why. 但这是行不通的,我无法一生找出原因。 The useful part of the error message I'm getting is: 我收到的错误消息的有用部分是:
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 `(+)`
The error comes about from trying to use 错误来自尝试使用
(+) :: (Num a) => a -> a -> a
as a parameter with type 作为类型的参数
(x -> u -> u -> u)
If you start trying to fit it in, remembering that (x -> u -> u -> u)
is the same as (x -> (u -> (u -> u)))
, 如果您开始尝试将其放入其中,请记住(x -> u -> u -> u)
与(x -> (u -> (u -> u)))
,
x == a
u == a
u -> u == a -> a == a
which is impossible, and where the error comes from. 这是不可能的,并且错误是从哪里来的。
Consider any of the following. 请考虑以下任一情况。
sumBFold :: (Num a) => BTree a -> a
sumBFold = foldB add3 where add3 x y z = x + y + z
sumBFold = foldB $ \x y z -> x + y + z
sumBFold = foldB ((.) (+) . (+))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.