为什么Haskell中的字符串被识别为(错误的)类型[Char]?
我有一个函数为什么Haskell中的字符串被识别为(错误的)类型[Char]?,haskell,Haskell,我有一个函数 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"
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]
,将第二个解释为字符串
?字符串
只是[Char]
的别名。定义如下:
type String = [Char]
Char
列表构成一个字符串
由于类型检查器试图将字符串
或[Char]
数据类型的“Test”与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
String
只是[Char]
的别名。定义如下:
type String = [Char]
Char
列表构成一个字符串
由于类型检查器试图将字符串
或[Char]
数据类型的“Test”与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
如果我理解正确,类型系统会说:“我有一个[Char]
,它不是Int->String
,所以我只是抛出了一个错误。”它甚至不会检查[Char]
是否适合String
,因为它已经知道它不正确了?我尝试了mytest=\x->“Test”
,这也可以用。或者,myTest=const“Test”
,因为const::a->b->a
@Dominik您的想法是绝对正确的,除了[Char]
和String
是等价的。@Dominik它说这是错误的,因为Int->String
意味着一个以Int为参数并返回字符串的函数。代码主体所做的只是返回一个没有任何参数的字符串。myTest
的类型是String
而不是Int->String
如果我理解正确,类型系统会说:“我有一个[Char]
,而那不是Int->String
,所以我只是抛出一个错误。”它甚至不会检查[Char]
将适合字符串
,因为它已经知道它不正确了?我尝试了mytest=\x->“Test”
,这也有效。或者,mytest=const“Test”
,因为const::a->b->a
@Dominik除了[Char]之外,你所想的是绝对正确的
和String
是等价的。@Dominik它说这是错误的,因为Int->String
表示一个以Int为参数并返回字符串的函数。代码主体所做的只是返回一个没有任何参数的字符串。myTest
的类型是String
notInt->String