2014-12-25 34 views
1

我有一個函數爲什麼Haskell中的字符串被識別爲(錯誤)類型[Char]?

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" 

有誰知道爲什麼哈斯克爾解釋第一個​​爲[Char],第二個爲String

回答

8

String只是[Char]的別名。它的定義如下:

type String = [Char] 

Char列表構成String

,因爲類型檢查嘗試匹配「測試」,這是與Int -> String型這會導致類型錯誤String[Char]數據類型你原來的功能沒有工作。你可以把它通過返回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 
+0

如果我理解正確的話,類型系統說:「我有一個'[字符]'這不是一個'詮釋 - > String'所以我只是拋出一個錯誤。」它甚至不檢查'[Char]'是否適合'String',因爲它已經知道它不正確? – Dominik

+0

我試過'mytest = \ x - >「Test」',這也適用。 – Dominik

+0

或者'myTest = const「Test」',因爲'const :: a - > b - > a'。 – utdemir

-2

嘛問題在於代碼被互相影響爲

mytest :: String 

而不是

mytest :: Int -> String 
相關問題