- 論壇徽章:
- 95
|
原帖由 win_hate 于 2009-1-20 21:58 發(fā)表 ![]()
# 為什么直接 map 到 [1..2] 上可以,但 map 到綁定到 l 上的 [1..2] 就不行呢?
這好像和 ghci 自動(dòng)做的一些轉(zhuǎn)換有關(guān)系。你用 :t 看看 [1..2] 和 l 的類型,就會(huì)發(fā)現(xiàn)它們并不一樣。
# Possible fix: add an instance declaration for (Fractional Integer)
這里說(shuō)的 instance 指的是什么? 是 / 這個(gè)運(yùn)算嗎?
這個(gè) instance 是和 type class 對(duì)應(yīng)的。type class 給出了運(yùn)算的接口,instance 給出具體的實(shí)現(xiàn)。Haskell 中運(yùn)算符重載就靠這個(gè)了。
Prelude> map (\x -> 1/x) l
<interactive>:1:11:
No instance for (Fractional Integer)
arising from a use of `/' at <interactive>:1:11-13
Possible fix: add an instance declaration for (Fractional Integer)
In the expression: 1 / x
In the first argument of `map', namely `(\ x -> 1 / x)'
In the expression: map (\ x -> 1 / x) l
上面這個(gè)錯(cuò)誤信息的意思是對(duì)于 type class Fractional 沒(méi)有和 Integer 對(duì)應(yīng)的實(shí)現(xiàn),在 GHCi 中,type class 的查看可通過(guò) :i, 如
Prelude> :i Fractional
class (Num a) => Fractional a where
(/) :: a -> a -> a
recip :: a -> a
fromRational :: Rational -> a
-- Defined in GHC.Real
instance Fractional Double -- Defined in GHC.Float
instance Fractional Float -- Defined in GHC.Float
可以看到,type class Fractional 定義了三個(gè)運(yùn)算,(/), recip, 和 fromRational,當(dāng)前環(huán)境中有兩個(gè)實(shí)現(xiàn)(instance),F(xiàn)ractional Double 和 Fractional Float。
你想要 (/) 用在 Integer 上(l 的類型為 [Integer]),就得添加一個(gè) instance Fractional Integer,也即對(duì) Integer 實(shí)現(xiàn) Fractional 的那三個(gè)操作。
[ 本帖最后由 MMMIX 于 2009-1-20 22:24 編輯 ] |
|