I finally started writing code for my thesis. Hooray!
To get my feet wet I decided to write a basic framework for evolutionary algorithms in Haskell. Nothing too major, just a way to easily assemble different evaluation, mutation and selection functions.
Turns out it’s a lot more difficult to do in Haskell.
Trouble starts as soon as you try generating a random population, because getting random numbers in Haskell is somewhat involved. Or rather, it looks scarily involved at first.
The main problem comes from how pseudo-random generators work. Essentially you start with a seed - it can be anything, I hear current time is a good starting seed – then every time somebody needs a new random number, you perform some formula on the seed and get a number.
The next number then depends on the previous number and so on until infinity. Your garden variety recursively defined series. Not very random at all, but works well enough for most.
Noticed the problem?
Yep, random generators rely on state and state is this hated, somewhat annoying thing to handle in Haskell. Monads may sound simple, but until you get the hang of them everything looks a bit odd.
Oh and you wouldn’t want to pollute your whole codebase with a monad just because you want to start your whole algorithm with some random stuff, would you?
No you wouldn’t, it’s messy.
After a lot of searching (and a lot of scary suggestions), this was the cleanest solution I could find:
import System.Random -- takes a random generator and returns a list of strings of 50 chars start_population :: (RandomGen g) => g -> [[Char]] start_population gen = [take 50 $ randomRs ('A', 'z') gen | x <- [0..]] main = do randomGen <- newStdGen -- get a random generator print $ take 2 $ start_population randomGen -- use it as a function argument
The best part about this approach is that Haskell automatically gives you a standard generator, which already takes a seed from some sort of input – not sure what it uses – so your results will look reasonably random.
But when you want to do testing, you can just as easily do this:
let rand = mkStdGen 42 print $ take 2 $ randomRs ('a', 'z') rand
Which will always print the same two characters “nd”.
Very useful when you want to test your code actually works!
There’s just one problem with this approach – it’s very difficult to up and decide that hey, this particular function right here, should be somewhat random from now on! You now have to tell the whole system and everyone using the function, that you’d like a random generator please.
Whether you should want to do that without telling anyone … well, that’s a whole other story.