无法与实际类型“[a]”匹配的预期类型“a” [英] Couldn't match expected type `a' with actual type `[a]'
问题描述
我能够完美地执行以下代码:
myLast :: [a] - > a
myLast [] =错误不能在空列表上调用myLast!
myLast(x:_)= x
但是我得到这个错误无法与实际类型[a]匹配的预期类型a。 `a'是一个刚性类型变量,由myLast的类型签名绑定:: [a] - >一个
为下面的代码:
myLast :: [a] - > a
myLast [] =错误不能在空列表上调用myLast!
myLast(_:x)= x
我是Haskell的初学者,错误消息太希腊和拉丁对我来说。根据我的理解,编译器无法在第二种情况下推断出类型。有人可以指点我到底发生了什么吗?
c $ c> [a] ,其余为 a
。 Haskell中的类型 a
的列表由并[a]
。 cons构造函数:
以头部和尾部为参数。
当您将列表解构为(x:y)
, x
是头部, y
是尾巴。所以在你的第二个代码片段中,当你的类型签名时,你绑定了列表类型的 tail ,列表类型为 [a]
要求你返回一个 a
类型的值(头部是一个例子)。
I was able to execute the following code flawlessly
myLast :: [a] -> a
myLast [] = error "Can't call myLast on an empty list!"
myLast (x:_) = x
but I'm getting this error Couldn't match expected type `a' with actual type `[a]'. `a' is a rigid type variable bound by the type signature for myLast :: [a] -> a
for the following code:
myLast :: [a] -> a
myLast [] = error "Can't call myLast on an empty list!"
myLast (_:x) = x
I'm a beginner in Haskell and the error message is too greek and latin for me. From what I can understand, the compiler is not able infer the type in the second case. Can someone point me to what is actually happening here?
You're declaring the input to be a list of type [a]
, and the rest to be of type a
.
A list of type a
in Haskell consists of a head of type a
and a tail, a list of type [a]
. The cons constructor :
takes the head and tail as its arguments.
When you deconstruct a list as (x:y)
, x
is the head and y
is the tail. So in your second code fragment, you're binding the tail of the list, which has the list type [a]
, when your type signature requires that you return a value of type a
(the head being one example).
这篇关于无法与实际类型“[a]”匹配的预期类型“a”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!