[英]Couldn't match expected type `a` with actual type `Integer`
I have a treeBuild
function does not get compiled, because the signature in the where clause: 我有一个
treeBuild
函数没有得到编译,因为where子句中的签名:
unfold :: (a -> Maybe (a,b,a)) -> a -> BinaryTree b
unfold f x = case f x of Nothing -> Leaf
Just (s,t,u) -> Node (unfold f s) t (unfold f u)
treeBuild :: Integer -> BinaryTree Integer
treeBuild n = unfold f 0
where f :: a -> Maybe (a,b,a)
f x
| x == n = Nothing
| otherwise = Just (x+1, x, x+1)
and I've got following compiler error: 而且我有以下编译器错误:
* Couldn't match expected type `a' with actual type `Integer'
`a' is a rigid type variable bound by
the type signature for:
f :: forall a b. a -> Maybe (a, b, a)
at D:\haskell\chapter12\src\Small.hs:85:16
* In the second argument of `(==)', namely `n'
In the expression: x == n
In a stmt of a pattern guard for
an equation for `f':
x == n
* Relevant bindings include
x :: a (bound at D:\haskell\chapter12\src\Small.hs:86:13)
f :: a -> Maybe (a, b, a)
(bound at D:\haskell\chapter12\src\Small.hs:86:11)
What is wrong with signature of f
? f
签名有什么问题?
In your program you write: 在您的程序中,您将编写:
treeBuild ::
Integer -> BinaryTree Integer
treeBuild
n = unfold f 0
where f ::
a -> Maybe (a,b,a)
f
x
|
x == n = Nothing
| otherwise = Just (x+1, x, x+1)
So that means that you want to check the equality between an Integer
and an a
. 因此,这意味着您要检查
Integer
和a
之间的相等性。 But (==)
has type signature: (==) :: Eq a => a -> a -> Bool
. 但是
(==)
具有类型签名: (==) :: Eq a => a -> a -> Bool
。 So that means in Haskell the two operands should have the same type . 因此,这意味着在Haskell中,两个操作数应具有相同的类型 。
You thus have two options: (1) you specify the f
function, or (2) you generalize the treeBuild
function. 因此,您有两个选择:(1)指定
f
函数,或者(2)概括treeBuild
函数。
f
function f
功能 treeBuild :: Integer -> BinaryTree Integer
treeBuild n = unfold f 0
where f ::
Integer -> Maybe (
Integer,Integer,Integer)
f x
| x == n = Nothing
| otherwise = Just (x+1, x, x+1)
Here we simply make f
a function f :: Integer -> Maybe (Integer,Integer,Integer)
. 在这里,我们简单地使
f
为函数f :: Integer -> Maybe (Integer,Integer,Integer)
。
treeBuild
function treeBuild
函数 We can - and this is more recommended - generalize the treeBuild
function (and slightly specialize the f
function): 我们可以-并建议这样做-泛化
treeBuild
函数(并稍微泛化f
函数):
treeBuild ::
(Num a, Eq a) => a -> BinaryTree
a
treeBuild n = unfold f 0
where f x
| x == n = Nothing
| otherwise = Just (x+1, x, x+1)
Then f
will have the type f ::
. (Num a, Eq a) => a -> Maybe (
a,a,a )
然后
f
将具有类型f :: (Num a, Eq a) => a -> Maybe (
。 a,a,a )
Since now we can build trees for any type that is a numerical type and supports equality. 从现在开始,我们可以为数字类型的任何类型构建树并支持相等性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.