PureScript Edition
A set of challenges for jump starting your understanding of monads.
This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.
You may have noticed that MCPrelude doesn’t have the Maybe
type or anything from Data.Maybe. That’s because you’re going to build it all yourself.
IMPORTANT Again, it is imperative that you DO NOT CHEAT. Don’t look at any of the Maybe
stuff from Prelude or Data.Maybe. Don’t do it. Nobody is forcing you to do these exercises, so you should try to get the maximum possible benefit. IMPORTANT
First of all, you need to define the Maybe
type. It should be able to represent any value a
, as well as the case where no value a
exists. This type needs to represent failing values of any type, so it needs a type variable similar to what we saw in the Gen
type synonym. But this can’t be a type synonym because it has two constructors. Write this type yourself and get it to compile. Once you’ve gotten it compiling, check your answer by hex decoding the following:
64617461204D617962652061203D204E6F7468696E67207C204A7573742061
You should use this definition and names going forward. We just wanted you to work on it yourself first.
Then for convenience write a Show
instance for this new type.
instance showMaybe :: Show a => Show (Maybe a) where
show :: (Maybe a) -> String
If you’re having trouble with this, here is the hex encoded instance.
696E7374616E63652073686F774D61796265203A3A2053686F772061203D3E2053686F7720284D617962652061292077686572650D0A202073686F77203A3A20284D61796265206129202D3E20537472696E670D0A202073686F77204E6F7468696E67203D20224E6F7468696E67220D0A202073686F7720284A757374206129203D20224A7573742022203C3E2073686F772061
You are also going to need an Eq
instance as well.
instance eqMaybe :: Eq a => Eq (Maybe a) where
eq :: Maybe a -> Maybe a -> Boolean
We’re not going to give you the answer to this one. In the worst case scenario you should be able to figure it out from the way the Show
instance was done.
On the other hand, if writing these instances was too difficult, it might be good to go study some more introductory PureScript materials before continuing here.