【发布时间】:2018-07-10 08:14:27
【问题描述】:
您好,在做 Real World Haskell 书中的示例时,我遇到了这个示例,但我无法理解它的含义以及它是如何工作的:instance Num a=>Num (SymbolicManip a)
在这种情况下,我应该翻译成类似:“对于类型为 SymbolicManip 的 Num 实例,有一个关于其类型为 a 的字段的约束,即:a 是 Num 本身的一个实例”?
有人可以告诉我我的解释是否正确或解释吗?
为什么instance Num (SymbolicManip a) 不够?
-- The "operators" that we're going to support
data Op = Plus | Minus | Mul | Div | Pow
deriving (Eq, Show)
{- The core symbolic manipulation type -}
data SymbolicManip a =
Number a -- Simple number, such as 5
| Arith Op (SymbolicManip a) (SymbolicManip a)
deriving (Eq, Show)
{- SymbolicManip will be an instance of Num. Define how the Num
operations are handled over a SymbolicManip. This will implement things
like (+) for SymbolicManip. -}
instance Num a => Num (SymbolicManip a) where
a + b = Arith Plus a b
a - b = Arith Minus a b
a * b = Arith Mul a b
negate a = Arith Mul (Number (-1)) a
abs a = error "abs is unimplemented"
signum _ = error "signum is unimplemented"
fromInteger i = Number (fromInteger i)
P.S所有代码均来自本书(chapter 13 - subchapter-Extended Example-Numeric Types)
【问题讨论】:
-
尝试在没有 Num 约束的情况下编译代码,看看会发生什么。