Saturday, June 25, 2011

Pete was right!

Yesterday¹ I had the good pleasure of speaking to my friend for the first time in too long. I always think it's always a shame when friends mutually forget to speak to each, but I suppose it's inevitable with the busy lives we lead.
Thankfully (or perhaps worryingly) in this instance facebook was there to remind me that we're friends.

One item which did come out of the conversation, and is pertinent to you the reader, is that I'm still not blogging as much as I used to. This is always a shame.

And much as I'd like to bore you with the details of my life, I'd much rather bore you with the details of my code! Some code which about which I was actually thinking "damn I need to post this", and I feel here is the ideal place:

For reasons which I may or may not detail in a forthcoming Blog, I am overjoyed to report that I have been writing a lot more Haskell again recently. After writing it for so many years I can safely say that I am still in awe of the language!

Let's have a look what I was up to:
keepOneIn n xs = getRandomRs (0,n-1) >>= return . map fst . filter ((==0) . snd) . zip xs
Now if you're not immediately jumping for joy, that's understandable, but if you are interested I'd like to walk you through this.
Firstly: What does it do?
Well, you give it a number (n) and a list of things (xs), and it will keepOneIn n of xs.
What does that look like? Well let's have a look at me using it in ghci:
Prelude> :module + Control.Monad.Random
Prelude Control.Monad.Random> let keepOneIn n xs = getRandomRs (0,n-1) >>= return . map fst . filter ((==0) . snd) . zip xs
Prelude Control.Monad.Random> evalRand (keepOneIn 3 [1..30]) (mkStdGen 0)
[2,5,7,8,10,14,15,18]

Here were see I am in ghci, I load the module Control.Monad.Random (which has the tools to help us to do things with randomness, I paste in the definition of keepOneIn from above, and then I have a go at using it. Because the keepOneIn function is "doing stuff with randomness" I have to evaluate it and that requires a psuedorandom number generator, hence the evalRand and then (mkStdGen 0) (the 0 is the seed for generator).
I have decided to keepOneIn 3 from the list [1..30]. We can see from the output the numbers which have randomly been kept, roughly one in three of the numbers from one to thirty.

And they say randomness in Haskell is hard work!



¹ Well, I'm not sure if it was a day ago. To be honest words like "yesterday" have somewhat lost there meaning since I desynchronised my sleeping from a 24-hour cycle. More to come in a later blog!

0 comments:

Post a Comment