Swizec Teller - a geek with a hatswizec.com

    Haskell and randomness

    I finally started writing code for my thesis. Hooray!

    A row of businesses in downtown Haskell.

    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.

    • Quasi-Random Number Generation in R

    Enhanced by Zemanta

    Did you enjoy this article?

    Published on July 2nd, 2012 in Algorithm, Haskell, Programming, Pseudorandom number generator, Pseudorandom Numbers, Random number generation, Uncategorized

    Learned something new?
    Want to become an expert?

    Here's how it works 👇

    Leave your email and I'll send you thoughtfully written emails every week about React, JavaScript, and your career. Lessons learned over 20 years in the industry working with companies ranging from tiny startups to Fortune5 behemoths.

    Join Swizec's Newsletter

    And get thoughtful letters 💌 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. 👌"

    ~ Ashish Kumar

    Join over 14,000 engineers just like you already improving their careers with my letters, workshops, courses, and talks. ✌️

    Have a burning question that you think I can answer? I don't have all of the answers, but I have some! Hit me up on twitter or book a 30min ama for in-depth help.

    Ready to Stop copy pasting D3 examples and create data visualizations of your own?  Learn how to build scalable dataviz components your whole team can understand with React for Data Visualization

    Curious about Serverless and the modern backend? Check out Serverless Handbook, modern backend for the frontend engineer.

    Ready to learn how it all fits together and build a modern webapp from scratch? Learn how to launch a webapp and make your first 💰 on the side with ServerlessReact.Dev

    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 ❤️

    Created bySwizecwith ❤️