为什么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
not
Int->String