3-Functor-2-Instances
- Implement
Functor
instances forEither e
and((->) e)
.
Solution for Either e
:
instance Functor (Either e) where
fmap :: (a -> b) -> Either e a -> Either e b
fmap _ (Left x) = Left x
fmap f (Right y) = Right (f y)
Proof:
To prove implementation is correct, we need to prove the following.
Solution for ((->) e)
.
Proof:
- Implement
Functor
instances for((,) e)
and forPair
, defined as
Solution for ((,) e)
:
Proof:
Solution for Pair
:
instance Functor Pair where
fmap :: (a -> b) -> Pair a -> Pair b
fmap f (Pair x y) = Pair (f x) (f y)
Proof:
Explain their similarities and differences.
- Implement a
Functor
instance for the typeITree
, defined as
Solution:
instance Functor ITree where
fmap :: (a -> b) -> ITree a -> ITree b
fmap f (Leaf g) = Leaf (f . g)
fmap f (Node xs) = Node $ map (fmap f) xs
Proof:
fmap id (Leaf f) = Leaf (id . f) = Leaf f = id (Leaf f)
fmap id (Node xs) = Node $ map (fmap id) xs = Node xs = id (Node xs)
The second to last equality can by proven by structural induction.
- Give an example of a type of kind
* -> *
which cannot be made an instance ofFunctor
(without usingundefined
).
Draft:
- Is this statement true or false?
The composition of two Functor
s is also a Functor
.
If false, give a counterexample; if true, prove it by exhibiting some appropriate Haskell code.
Draft:
Proof: