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.

Build a library of things that can fail

Now that you have a Maybe type, you need to use it. So now use it to build safe versions of several common functions specified by the Prelude.

headMay :: [a] -> Maybe a
tailMay :: [a] -> Maybe [a]
lookupMay :: Eq a => a -> [(a, b)] -> Maybe b
divMay :: (Eq a, Fractional a) => a -> a -> Maybe a
maximumMay :: Ord a => [a] -> Maybe a
minimumMay :: Ord a => [a] -> Maybe a

The functions headMay and tailMay are “safe” versions of the well known head and tail functions. The former returns the first element of a list or Nothing if the list is empty. The latter returns a list containing all but the first element of a list, or Nothing if the list is empty. The lookupMay function is kind of like the lookup for a map. Find the first tuple in the list where the first element is the equal to the passed in value and return the second element. If there is no matching a, then return Nothing. The divMay function should return Nothing if you’re dividing by 0 and the result of the division otherwise. maximumMay and minimumMay calculate the maximum and minimum respectively of all the numbers in the list, but if the list is empty they return Nothing.

Previous Page - Next Page