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.
For starters I'm going to evolve a "Hello World!" string. How hard could it be? Took me an hour to evolve a poem in python based on character mutations ...
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.
Random Generators
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.
Continue reading about Haskell and randomness
Semantically similar articles hand-picked by GPT-4
- Markov chain poem trainer+generator in 29 sloc of Haskell
- An elegant way to randomly change every list member in Haskell
- Evolving a poem with an hour of python hacking
- Livecoding #38 - A faux AI that writes JavaScript
- Learning me a Haskell
Learned something new?
Read more Software Engineering Lessons from Production
I write articles with real insight into the career and skills of a modern software engineer. "Raw and honest from the heart!" as one reader described them. Fueled by lessons learned over 20 years of building production code for side-projects, small businesses, and hyper growth startups. Both successful and not.
Subscribe below 👇
Software Engineering Lessons from Production
Join Swizec's Newsletter and get insightful emails 💌 on mindsets, tactics, and technical skills for your career. Real lessons from building production software. No bullshit.
"Man, love your simple writing! Yours is the only newsletter I open and only blog that I give a fuck to read & scroll till the end. And wow always take away lessons with me. Inspiring! And very relatable. 👌"
Have a burning question that you think I can answer? Hit me up on twitter and I'll do my best.
Who am I and who do I help? I'm Swizec Teller and I turn coders into engineers with "Raw and honest from the heart!" writing. No bullshit. Real insights into the career and skills of a modern software engineer.
Want to become a true senior engineer? Take ownership, have autonomy, and be a force multiplier on your team. The Senior Engineer Mindset ebook can help 👉 swizec.com/senior-mindset. These are the shifts in mindset that unlocked my career.
Curious about Serverless and the modern backend? Check out Serverless Handbook, for frontend engineers 👉 ServerlessHandbook.dev
Want to Stop copy pasting D3 examples and create data visualizations of your own? Learn how to build scalable dataviz React components your whole team can understand with React for Data Visualization
Want to get my best emails on JavaScript, React, Serverless, Fullstack Web, or Indie Hacking? Check out swizec.com/collections
Did someone amazing share this letter with you? Wonderful! You can sign up for my weekly letters for software engineers on their path to greatness, here: swizec.com/blog
Want to brush up on your modern JavaScript syntax? Check out my interactive cheatsheet: es6cheatsheet.com
By the way, just in case no one has told you it yet today: I love and appreciate you for who you are ❤️