我有一个功能
mytest :: Int -> String
mytest = "Test"
ghci拒绝加载文件:
Couldn't match expected type ‘Int -> String’
with actual type ‘[Char]’
In the expression: "Test"
In an equation for ‘mytest’: mytest = "Test"
Failed, modules loaded: none.
添加通配符运算符后,一切正常:
mytest :: Int -> String
mytest _ = "Test"
有谁知道为什么Haskell将第一个"Test"
解释为[Char]
而第二个解释为String
?
答案 0 :(得分:8)
String
只是[Char]
的别名。它的定义如下:
type String = [Char]
Char
列表构成String
。
您的原始功能无法正常工作,因为类型检查器正在尝试匹配“Test”,这是String
或[Char]
数据类型Int -> String
类型导致类型错误。您可以通过返回Int -> String
类型的函数
mytest :: Int -> String
mytest = \x -> show x
也可以写成:
mytest :: Int -> String
mytest x = show x
或者你已经完成了:
mytest :: Int -> String
mytest _ = "Test" -- Return "Test" no matter what the input is