I’m trying to understand this example a little better
data Tuple a b = Tuple a b deriving (Eq, Show)
newtype Flip f a b = Flip (f b a) deriving (Eq, Show)
-- `f` is a type that has an instance `Functor` and two arguments: `a` and `b`
-- `Flip` returns the same type `f` with `a` and `b` reversed
instance Functor (Flip Tuple a) where
fmap f (Flip (Tuple x y)) = Flip $ Tuple (f x) y
aa :: Flip Tuple String Integer
aa = fmap (+1) (Flip (Tuple 1 "blah"))
-- Flip (Tuple 2 "blah")
What I get is:
- In
fmap
on the left side of=
,(Tuple x y)
get’s itsx
andy
reversed. - On the right side of
=
f
is applied tox
and then theTuple
with the new value forx
is flipped again.
What I don’t get is:
- I expected
Tuple x y
to becomeTuple y x
- And I’m guessing it is, except that
x
is nowy
andy
is nowx
- But since the order
x y
hasn’t change I’m left wondering what has changed?
Here is my best/current guess on that is:
- Before the flip
x
on the LHS has the value ofa
in the declaration line. (I’m doubtinga
actually has a value?) - After the flip
y
has the value ofa
- Therefore
x
is no longer part of the structure and can now be changed by applyingf
- Then the type is flipped again to the original order.