2017-08-07 32 views
1

我試圖在ghci控制檯中做最簡單的事情。我希望能夠擁有類型[Maybe Int]的值。但無論Nothing : [1, Nothing][1, Nothing] ++ [Nothing]給人,我覺得很難理解的錯誤:由於使用'it'而導致的(Num(也許a0))的實例

No instance for (Num (Maybe a0)) arising from a use of ‘it’ 
    In the first argument of ‘print’, namely ‘it’ 
    In a stmt of an interactive GHCi command: print it 

請能有人解釋這個錯誤,並提出如何解決它?

+3

'[1,沒什麼]'?在Haskell中,列表只包含一種元素。 –

+0

我想能夠擁有'[Maybe Int]'類型的值。我必須明確指定它嗎? – altern

+0

您需要在'Just'構造函數中包裝'1'('只有1')。'Nothing'與其他語言中的'null'不同,它只是'Maybe'的空構造函數。 – ryachza

回答

7

簡短回答:你可能要寫[Just 1,Nothing]

說明

在Haskell,一個列表可以包含僅一種類型的元素的。所以你不能在同一個列表中混合例如Int s和String s。

如果你寫:

[1, Nothing] 

哈斯克爾將致力於獲得的類型。由於你已經寫了一個Nothing,Haskell推導出該列表包含Maybe a類型的元素(它不知道哪個a)。現在它想要將1轉換爲Maybe a。數字文字可以轉換爲任何類n與類型Num n。但沒有a其中Maybe aNum (Maybe a),所以Haskell會在這個錯誤。

但是,您可以使用,因爲哈斯克爾Just 1然後將推導的Maybe aa有類型類Num a

Prelude> :t [Just 1,Nothing] 
[Just 1,Nothing] :: Num a => [Maybe a] 
7

在Haskell中,列表(即,的[a]類型的東西)只能包含單個類型的值(a)。

哈斯克爾還具有多態數字文本,所以如果我們限制類型的1誤差會稍微更清晰:

λ Nothing : [1 :: Int, Nothing] 

<interactive>:1:12: error: 
    • Couldn't match expected type ‘Maybe a’ with actual type ‘Int’ 
    • In the expression: 1 :: Int 
     In the second argument of ‘(:)’, namely ‘[1 :: Int, Nothing]’ 
     In the expression: Nothing : [1 :: Int, Nothing] 
    • Relevant bindings include 
     it :: [Maybe a] (bound at <interactive>:1:1) 

NothingMaybe a類型,1 :: IntInt類型。類型檢查程序無法找到 使Maybe aInt爲相同類型,因此它會報告錯誤。

如果你想有一些值的列表和一些Nothing S,你需要使用Maybe aJust構造:

Just :: a -> Maybe a 

所以,你可以這樣做:

λ Nothing : [ Just 1, Nothing ] 
[Nothing,Just 1,Nothing] 
相關問題