为什么Haskell中的String被识别为(错误)类型[Char]?

Dom*_*nik 1 haskell

我有一个功能

mytest :: Int -> String
mytest = "Test"
Run Code Online (Sandbox Code Playgroud)

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.
Run Code Online (Sandbox Code Playgroud)

添加通配符运算符后,一切正常:

mytest :: Int -> String
mytest _ = "Test"
Run Code Online (Sandbox Code Playgroud)

有谁知道为什么Haskell将第一个解释"Test"[Char]第二个和第二个String

Sib*_*ibi 8

String只是一个别名[Char].它的定义如下:

type String = [Char]
Run Code Online (Sandbox Code Playgroud)

一份清单Char构成一份String.

因为类型检查尝试匹配"测试",这是一个你原来的功能没有工作String[Char]数据类型为Int -> String类型导致类型错误.您可以通过返回Int -> String类型的函数使其工作:

mytest :: Int -> String
mytest = \x -> show x
Run Code Online (Sandbox Code Playgroud)

也可以写成:

mytest :: Int -> String
mytest x = show x 
Run Code Online (Sandbox Code Playgroud)

或者像你一样:

mytest :: Int -> String
mytest _ = "Test"  -- Return "Test" no matter what the input is
Run Code Online (Sandbox Code Playgroud)

  • @Dominik它说这是错的,因为`Int - > String`意味着一个以int作为参数的函数,并返回一个字符串.代码的主体所做的只是返回一个没有任何参数的字符串.`myTest`的类型是`String`而不是`Int - > String` (2认同)