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

时间:2014-12-25 16:08:36

标签: 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"

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

1 个答案:

答案 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