The Monad Challenges

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

This project is 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 return. 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 []. You can do this for Maybe and [] 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.hs (again using the same header we’ve been using and importing MCPrelude instead of Haskell’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.hs 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 :: 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 Learn You a Haskell.

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

6E6577747970652047656E2061203D2047656E207B2072756E47656E203A3A2053656564202D3E2028612C205365656429207DDADA696E7374616E6365204D6F6E61642047656E207768657265DA2020202072657475726E203D202E2E2EDA2020202062696E64203D202E2E2E

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