The Monad Challenges

PureScript Edition

A set of challenges for jump starting your understanding of monads.

Outline

Set 1: Random Numbers

Set 2: Failing Computations

Set 3: Combinations

Set 4: Common Abstraction

Set 5: Do Notation

MCPrelude documentation

This project is maintained by shaunplee and is a fork of the Monad Challenges maintained by mightybyte

Creative Commons License
This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

Creating Instances

Now you have a Monad type class with two functions: bind and pure. If you’ve heard anything about monads in the past, this might sound familiar. But don’t go off and look at existing monad code yet. You have a lot more ground to discover yourself.

The next thing you need to do is create instances of your Monad type class for the three types we’ve been working with: Gen, Maybe, and Array. You can do this for Maybe and Array with no trouble. But Gen won’t work because it is a type synonym. First you need to replace your type synonym with a newtype. Don’t go back and modify your old code. We’ll be referring back to that in the future. Do this work in a new file Set4.purs (again using the same header we’ve been using and importing MCPrelude instead of PureScript’s Prelude). You can import Set2 because that has your Maybe data type and associated code which can be reused. But don’t import Set1. When you are finished with this challenge you should have a Set4.purs file with a Monad type class, a Gen newtype, and three instances.

Along with your Gen newtype you also might want to write a helper function to make it easier to get your random values out:

evalGen :: forall a. Gen a -> Seed -> a

If you did all the exercises properly this should be pretty straightforward. The Monad instance for Gen may be a little bit less obvious because this time you’ll have to do some newtype wrangling.

If you need to brush up your knowledge of some of these topics, check out this chapter on newtypes or this chapter on type classes in PureScript by Example.

If you’re having trouble with the newtype instance here’s a hex encoded code template to get you started:

6E6577747970652047656E2061203D2047656E202853656564202D3E205475706C6520536565642061290D0A0D0A696E7374616E6365206D6F6E616447656E203A3A204D6F6E61642047656E2077686572650D0A202070757265203D202E2E2E0D0A202062696E64203D202E2E2E

Again, if possible try not to use this. We’re still leaving the hard bits out. These things are worth fighting with for awhile.

Previous Page - Next Page