我正在玩一些Haskell代碼。我定義了兩個函數:Haskell的類型關聯鏈令人費解
count :: [a] -> Int
count [] = 0
count (x:xs) = 1 + (count xs)
-- 03. Write a function that computes the mean of a list, i.e., the sum of all
-- elements in the list divided by its length. (You may need to use the
-- fromIntegralfunction to convert the length of the list from an integer
-- into a floating-point number.)
-- I've guessed this type definition, but it's incorrect:
-- listMean :: [a] -> Double
-- The following is the same inferred by hgci
listMean :: (Fractional a) => [a] -> a
listMean lst = (foldl1 (+) lst)/(fromIntegral (count lst))
爲什麼[a] - > Double不正確?看來,我給出了lst,這是一個類型a的通用列表,listMean返回一個Double。我究竟做錯了什麼?
感謝, 阿爾弗雷多
+1,非常好的解釋。 – 2010-11-02 19:11:33
完美!非常感謝你! – 2010-11-02 19:19:28