I'm reading Bartosz's awesome blog, and following along on challenge question 3, I'm a bit stumped:
https://bartoszmilewski.com/2015/04/07/natural-transformations/
Q3: define some natural transformations from Reader Bool
to Maybe
I have defined the Reader functor as:
newtype Reader e a = Reader (e->a)
runReader :: Reader e a -> e -> a
runReader (Reader f) env = f env
instance Functor (Reader e) where
fmap f (Reader g) = Reader (\x -> f (g x))
and I want to find a natural transformation
n :: Reader Bool a -> Maybe a
My intuition is that if Reader
's environment is True
, I can have a Just a
, and if False
, then the natural transformation projects to Nothing
. But that feels slightly monadic, or like a Maybe
nested inside a Reader
, like Reader Bool (Maybe Int)
, so I'm not sure.
I can't concieve of how to do that. The best I have is:
n :: Reader Bool a -> Maybe a
n (Reader f) = Just (f True)
But this cannot take into account the environment, nor return Nothing
.
I want to build a structure that commutes, building a square out of fmap
, and natural transformations.
For ex:
nat
Reader Bool Int +---------------------------> Maybe Int
+ +
| |
| |
| |
| fmap show | fmap show
| |
| |
| |
| |
v nat v
Reader Bool String +--------------------------> Maybe String
can you help me fill in the gaps?
As I've already said in a comment, you want n to use the environment, but, since you have only the Reader, there is no environment and you have to provide it yourself.
Evidently, these are in fact three distinct natural transformations Reader Bool a -> Maybe a
:
n (Reader f) = Just (f True)
n (Reader f) = Just (f False)
n (Reader f) = Nothing
Let's prove there are no more. In category-theoretic terms, the functor Reader Bool a
is just Hom(Bool,_)
. Now, Yoneda lemma tells us that
Nat(Hom(X,_), F) = F(X)
That is, natural transformations from the functor Hom(X,_)
to a functor F
are in one-to-one correspondence with elements of the set F(X)
.
In our case, X = Bool
and F = Maybe
, so we obtain
Nat(Hom(Bool,_),Maybe) = Maybe Bool
Maybe Bool
contains exactly three elements: Just True
, Just False
and Nothing
, which correspond to the implementations in the beginning of the answer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With