这个功能有什么问题?
test :: Show s => s
test = "asdasd"
Run Code Online (Sandbox Code Playgroud)
String是Show类的一个实例,所以看起来是正确的.
错误是
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"
Run Code Online (Sandbox Code Playgroud)
sep*_*p2k 37
test :: Foo a => a表示"对于任何类型的实例Foo,test是该类型的值".所以,在这里你可以使用类型的值的任何地方X,其中X的一个实例Foo,你可以使用类型的值Foo a => a.
类似于test :: Num a => a; test = 42作品的东西因为42可以是类型的值Int或者Integer或者Float是其他任何实例的值Num.
然而"asdasd",不能是一个Int或任何其他的实例Show- 它只能是一个String.因此,它与类型不匹配Show s => s.
小智 8
是的,String是一个实例Show.但是这不允许使用字符串作为abritary Show值.1可能是Num a => a因为有一个1 :: Integer,一个1 :: Double,一个1 :: Word16等.如果"asdasd"可能的类型Show a => a,将有"asdasd" :: Bool,"asdasd" :: String,"asdasd" :: Int,等没有.因此,"asdasd"不能是类型Show a => a.字符串常量的类型没有比它更通用String.