apprendimento Haskell e io non sono sicuro perché non ottengo il risultato atteso, dato queste definizioni:Non capisco perché questo modello corrisponde guardia
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
Ho scritto questa funzione
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
Tuttavia :
*HW05> squashMul (Lit 5) (Lit 1)
Lit 1
Se scrivo una versione specifica per 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
Quindi ho ottenuto il risultato previsto.
Perché (Lit mulId) <- x
corrisponde anche quando x non lo è (Lit 1)?
'mulId' è una nuova variabile locale, non correlata a quella precedentemente definita. Vuoi 'Lit w <- x, w == mulId = ...' invece. – chi