2010-01-14 55 views
1

我有以下表現:哈斯克爾 - 更多的類型推斷問題

getCount :: (Num a) => a -> [a] 
getCount int = foldl 
     processOneCount 
     [0,0,0,0,0,0,0,0,0,0] 
     (map (singleDigitCount) (map (digitToInt) (show int))) 

,我也得到了以下錯誤:

Couldn't match expected type `a' against inferred type `Int' 
    `a' is a rigid type variable bound by 
     the type signature for `getCount' 
     at C:\Users\RCIX\Desktop\Haskell Code\test.hs:23:17 
    Expected type: [a] 
    Inferred type: [Int] 
In the expression: 
    foldl 
     processOneCount 
     [0, 0, 0, 0, ....] 
     (map (singleDigitCount) (map (digitToInt) (show int))) 
In the definition of `getCount': 
    getCount int 
       = foldl 
        processOneCount 
        [0, 0, 0, ....] 
        (map (singleDigitCount) (map (digitToInt) (show int))) 

然而,當我做了:t [0,0,0,0,0,0,0,0,0,0]我回來[0,0,0,0,0,0,0,0,0,0] :: (Num t) => [t]。那麼爲什麼我不能在第一個表達式中使用它?

回答

4

您使用的是digitToInt,它返回一個Int,而不是輸入類型。

+0

哦。我應該堅持一個int類型,還是有辦法強制輸出成Num? – RCIX 2010-01-14 22:11:43

+3

'fromIntegral ::(Integral a,Num b)=> a - > b' – ephemient 2010-01-14 22:12:49

+0

感謝您的幫助:) – RCIX 2010-01-14 22:15:41

0

查克是正確的。爲了避免弄亂你的代碼,你可以使用.運營商添加所需的功能:

(map (singleDigitCount) (map (fromIntegral . digitToInt) (show int))) 

這是假設該singleDigitCountprocessOneCount也任意數字類型的工作。