<div dir="ltr">In the following code, function fmap does not compile because variable 'y' on line marked <***> has type (Expr a) where an (Expr b) is expected.  The code can be fixed simply by returning (Val x) on the rhs of the function but then we are allocating a new object for something we could potentially reuse since (Val n) has the same runtime representation in (Expr a) and (Expr b) (it has no dependence on the type variable).<div><br></div><div>I was reading about coerce (Data.Coerce) recently and thought this could be a place it could be used but simply replacing the 'y' on the rhs with 'coerce y' does not compile (error message below).</div><div><br></div><div>Is it possible to use coerce in this context?</div><div><br></div><div>Thanks for any help,</div><div>Brent<br><div><br></div><div><div>=======================================</div><div><div class="gmail_default" style="font-family:"comic sans ms",sans-serif"></div></div></div><div><font face="arial, sans-serif">data Expr a = Var a | Val Int | Add (Expr a) (Expr a)<br>  deriving Show<br><br>instance Functor Expr where<br>  fmap :: (a -> b) -> Expr a -> Expr b<br>  fmap f (Var a) = Var (f a)<br>  fmap f (Add e0 e1) = Add (fmap f e0) (fmap f e1)<br>  fmap _ y@(Val x) = y   -- <***></font><br></div></div><div><font face="arial, sans-serif"><br></font></div><div>=======================================</div><div><div class="gmail_default" style="font-family:"comic sans ms",sans-serif">/dev/proj/src/Ex12.hs:69:22: error:<br>    • Couldn't match representation of type ‘a’ with that of ‘b’<br>        arising from a use of ‘coerce’<br>      ‘a’ is a rigid type variable bound by<br>        the type signature for:<br>          fmap :: forall a b. (a -> b) -> Expr a -> Expr b<br>        at /dev/proj/src/Ex12.hs:66:11-38<br>      ‘b’ is a rigid type variable bound by<br>        the type signature for:<br>          fmap :: forall a b. (a -> b) -> Expr a -> Expr b<br>        at /dev/proj/src/Ex12.hs:66:11-38<br>    • In the expression: coerce y<br>      In an equation for ‘fmap’: fmap _ y@(Val _) = coerce y<br>      In the instance declaration for ‘Functor Expr’<br>    • Relevant bindings include<br>        y :: Expr a (bound at /dev/proj/src/Ex12.hs:69:10)<br>        fmap :: (a -> b) -> Expr a -> Expr b<br>          (bound at /dev/proj/src/Ex12.hs:67:3)<br>   |<br>69 |   fmap _ y@(Val _) = coerce y<br>   |                      ^^^^^^^^<font color="#888888"><br></font></div><font color="#888888"><div><div>=======================================</div></div></font></div></div>