考虑这种类型:
newtype Ap f a = Ap (f a)
instance (Applicative f, Num a) => Num (Ap f a) where
(+) = liftA2 (+)
(*) = liftA2 (*)
negate = fmap negate
fromInteger = pure . fromInteger
abs = fmap abs
signum = fmap signum
f
该实例合法需要满足什么条件?显然,仅仅作为一个合法Applicative
的是不够的(例如,与when isx + negate x
不同,即使是一个合法的)。我的猜测是,成为一个可表示的函子既是必要的又是充分的。不过,我不确定如何证明这一点(或者如果它是错误的,则找到一个反例)。fromInteger 0
x
Ap Nothing
Maybe
Applicative
f
为了参考起见,以下是文档建议的Num
法律:
-- Associativity of (+)
(x + y) + z = x + (y + z)
-- Commutativity of (+)
x + y = y + x
-- fromInteger 0 is the additive identity
x + fromInteger 0 = x
-- negate gives the additive inverse
x + negate x = fromInteger 0
-- Associativity of (*)
(x * y) * z = x * (y * z)
-- fromInteger 1 is the multiplicative identity
x * fromInteger 1 = x
fromInteger 1 * x = x
-- Distributivity of (*) with respect to (+)
a * (b + c) = (a * b) + (a * c)
(b + c) * a = (b * a) + (c * a)