- 论坛徽章:
- 95
|
原帖由 win_hate 于 2009-1-20 21:58 发表 ![]()
# 为什么直接 map 到 [1..2] 上可以,但 map 到绑定到 l 上的 [1..2] 就不行呢?
这好像和 ghci 自动做的一些转换有关系。你用 :t 看看 [1..2] 和 l 的类型,就会发现它们并不一样。
# Possible fix: add an instance declaration for (Fractional Integer)
这里说的 instance 指的是什么? 是 / 这个运算吗?
这个 instance 是和 type class 对应的。type class 给出了运算的接口,instance 给出具体的实现。Haskell 中运算符重载就靠这个了。
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
上面这个错误信息的意思是对于 type class Fractional 没有和 Integer 对应的实现,在 GHCi 中,type class 的查看可通过 :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 定义了三个运算,(/), recip, 和 fromRational,当前环境中有两个实现(instance),Fractional Double 和 Fractional Float。
你想要 (/) 用在 Integer 上(l 的类型为 [Integer]),就得添加一个 instance Fractional Integer,也即对 Integer 实现 Fractional 的那三个操作。
[ 本帖最后由 MMMIX 于 2009-1-20 22:24 编辑 ] |
|