学习 Haskell,我不确定为什么我没有得到预期的结果,给定这些定义:
instance Ring Integer where
addId = 0
addInv = negate
mulId = 1
add = (+)
mul = (*)
class Ring a where
addId :: a -- additive identity
addInv :: a -> a -- additive inverse
mulId :: a -- multiplicative identity
add :: a -> a -> a -- addition
mul :: a -> a -> a -- multiplication
我写了这个函数
squashMul :: (Ring a) => RingExpr a -> RingExpr a -> RingExpr a
squashMul x y
| (Lit mulId) <- x = y
| (Lit mulId) <- y = x
squashMul x y = Mul x y
然而:
*HW05> squashMul (Lit 5) (Lit 1)
Lit 1
如果我专门为 Integer 编写一个版本:
squashMulInt :: RingExpr Integer -> RingExpr Integer -> RingExpr Integer
squashMulInt x y
| (Lit 1) <- x = y
| (Lit 1) <- y = x
squashMulInt x y = Mul x y
然后我得到了预期的结果。
为什么(Lit mulId) <- x
即使 x 不是 (Lit 1) 也匹配?