Learning Haskell i nie jestem pewien, dlaczego nie uzyskać oczekiwany rezultat, biorąc pod uwagę te definicje:Nie wiem, dlaczego ten strażnik wzorzec pasuje
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
Napisałem tę funkcję
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
jednak :
*HW05> squashMul (Lit 5) (Lit 1)
Lit 1
Jeśli piszę jedna wersja specjalnie dla 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
Otrzymuję oczekiwany wynik.
Dlaczego (Lit mulId) <- x
pasuje nawet, gdy x nie jest (Lit 1)?
'mulId' jest nową zmienną lokalną, niezwiązaną z poprzednio zdefiniowaną. Zamiast tego chcesz "Lit w <- x, w == mulId = ...". – chi