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.

Random Number Generation

In MCPrelude we provide a simple random number generation function rand. Random number generators usually rely on mutable state side effects. They maintain some state somewhere in memory and use that to figure out what “random” number to give you. Before the function returns, it modifies the mutable state so that the next time you call the function you’ll get a different number. PureScript is a pure functional programming language and because our custom Prelude hides PureScript’s mechanisms for dealing with side effects, we can’t build a random number generator that way. Our random number generator has to have everything it needs passed in and it has to return everything it modifies. Therefore, it has this type signature:

rand :: Seed -> Tuple Seed Int

You can construct seeds with the mkSeed function.

mkSeed :: Int -> Seed

Make a function that gives you the first five random numbers starting with a seed of (mkSeed 1). Call it:

fiveRands :: Array Int

For now don’t try to do anything fancy. Just implement it in the most straightforward way that comes to mind. To check your answers, the product of these numbers is 492745054.

Previous Page - Next Page