Randomness is a bit of a strange concept in Haskell.

As I discovered writing about Haskell and Randomness a few weeks ago, the best way to avoid doing everything inside the IO monad is to write functions that always return the random generator.

The crux of the matter is that random generators are long mathematical sequences. If you keep using the same index, you’ll keep getting the same “random” value. You haveย to make sure the random generator progresses.

Increasing a number by a random value would look something like this:

import System.Random
 
addRand::(RandomGen g) => g -> Int -> (g, Int)
addRand gen x = let (a, gen') = randomR (0, 20) gen
                in (gen', x+a)
main = do
  generator <- newStdGen
 
  print $ snd $ addRand generator 5
  -- prints 15

While this approach is great for changing a single value, it breaks down when you try to randomly change a whole list:

  print $ map (snd . (addRand generator)) [1,1,1,1]
  -- prints [11,11,11,11]

Bummer! We applied a random function to every list member. And got a list of identical values!

The problem is that every time addRandย gets called, it uses the same random generator. This means we’re always using the same number in the random generator series.

We need a way to perform a fold and a map at the same time. A map, so the function is applied to every list item and we get a new list, and a fold where the generator is used as the accumulator.

We might be tempted to write something like this monstrosity:

addRand'::(RandomGen g) => g -> [Int] -> [(g, Int)]
addRand' gen [x] = [addRand gen x]
addRand' gen (x:xs) = let (gen', x') = addRand gen x
                     in (gen', x'):(addRand' gen' xs)
 
-- and then in main
  print $ map (snd) $ addRand' generator [1,1,1,1]
  -- prints [11,3,13,14]

This works. Every number in the list is different!

But the code is somewhat terrible and difficult to reason about.

Luckily, Haskell has got us covered and comes with a standard function called mapAccumL, which is a combination of a fold and a map:

  print $ snd $ mapAccumL addRand generator [1,1,1,1]
  -- prints [11,3,13,14]

Cleaner, less work, more obvious what’s going on. And it just happens to be perfect for writing evolutionary algorithms in Haskell. But more on that later, hopefully as early as Friday.

Here’s the whole code:

 
import System.Random
import Data.List
 
addRand::(RandomGen g) => g -> Int -> (g, Int)
addRand gen x = let (a, gen') = randomR (0, 20) gen
                in (gen', x+a)
 
addRand'::(RandomGen g) => g -> [Int] -> [(g, Int)]
addRand' gen [x] = [addRand gen x]
addRand' gen (x:xs) = let (gen', x') = addRand gen x
                     in (gen', x'):(addRand' gen' xs)
 
main = do
  generator <- newStdGen
 
  print $ snd $ addRand generator 5
  -- prints 15
 
  print $ map (snd . (addRand generator)) [1,1,1,1]
  -- prints [11,11,11,11]
 
  print $ map (snd) $ addRand' generator [1,1,1,1]
  -- prints [11,3,13,14]
 
  print $ snd $ mapAccumL addRand generator [1,1,1,1]
  -- prints [11,3,13,14]
Enhanced by Zemanta

Learned something new? Want to become a better engineer? ๐Ÿ’Œ

Join 9,400+ people just like you already improving their skills.

Here's how it works ๐Ÿ‘‡

Leave your email and I'll send you an Interactive Modern JavaScript Cheatsheet ๐Ÿ“– right away. After that you'll get a thoughtfully written email every week aboutย React, JavaScript,ย  andย lessons learned in my 20 years of writing code for companies ranging from tiny startups to Fortune5 behemoths.



Man, I love your way of writing these newsletters. Often very relatable and funny perspectives about the mundane struggles of a dev. Lightens up my day. ~ Kostas

PS: You should also follow me on twitter ๐Ÿ‘‰ here.
It's where I go to shoot the shit about programming.