问题描述
此功能有什么问题?
test :: Show s => s
test = "asdasd"
String是Show
类的实例,因此似乎正确.
String is an instance of the Show
class, so it seems correct.
错误是
src\Main.hs:224:7:
Couldn't match expected type `s' against inferred type `[Char]'
`s' is a rigid type variable bound by
the type signature for `test' at src\Main.hs:223:13
In the expression: "asdasd"
In the definition of `test': test = "asdasd"
推荐答案
test :: Foo a => a
的意思是对于任何作为Foo
实例的类型,test
都是该类型的值".因此,在可以使用X
类型的值(其中X
是实例Foo
)的任何地方,都可以使用类型Foo a => a
的值.
test :: Foo a => a
means "for any type which is an instance of Foo
, test
is a value of that type". So in any place where you can use a value of type X
where X
is an instance Foo
, you can use a value of type Foo a => a
.
之所以可以使用test :: Num a => a; test = 42
之类的东西,是因为42可以是Int
或Integer
或Float
类型的值,或者是Num
实例的其他任何值.
Something like test :: Num a => a; test = 42
works because 42 can be a value of type Int
or Integer
or Float
or anything else that is an instance of Num
.
但是"asdasd"
不能是Int
或作为Show
实例的任何其他内容-它只能是String
.因此,它与Show s => s
类型不匹配.
However "asdasd"
can't be an Int
or anything else that is an instance of Show
- it can only ever be a String
. As a consequence it does not match the type Show s => s
.
这篇关于无法将预期类型与推断类型,刚性类型变量错误进行匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!