Saturday, August 31, 2013

How to generate UUID using Haskell - Part - 1

Well well, what do we have here, in my poor attempt to learn Haskell, I thought it would be great if I document my findings.  This will not only help me understand the concepts better but also might help others who are faced with a similar problem.

UUID could be a great candidate when we want to generate some sort of a random unique string.  Last night I was faced with a similar situation, I had to generate UUID values in Haskell. I looked around and found two ways of doing it.  One way is pretty straight forward and that's what we are going to cover in this post.

How do they do it!

Haskell has a package called system-uuid which could help us generate UUID values.  To install the package using cabal fun the following command

For me the installation failed the first time around.  The reason for the failure was that, the system-uuid package generates UUID using native generators.  The Ubuntu system on which I was running didn't have uuid-dev package installed on it.  Here is the command to install the uuid-dev package on Ubuntu.
After this if we run the cabal install command again it should work.

Now to generate the UUID from the System.UUID.V4 was pretty straightforward.
  • This module has a method called uuid which will return UUID value wrapped with IO monad i.e.  IO Data.UUID.UUID.  
  • What happens when we call this method more than once?  Will it return different value or same value all the time?
  • Haskell is a pure language, which means result of a function call is fully determined by the arguments passed to the function. 
  • The uuid function would be useless if it returns the same value when called multiple times.  The functions that return values wrapped in IO monad can return different values when called multiple times.  A good explanation of how this is implemented can be found here.  This essentially enables our uuid function to return different value when called multiple times.  
  • To see this in action, lets start the GHCI i.e. the Haskell Interpretter
  • Load the module System.UUID.V4
  • Type uuid on the prompt.
  • A bunch of packages would be loaded and then the last statement should be the UUID value printed on the console.
Thats all folks! In the next post I will explain how to generate UUID value without using the system-uuid package.
Have some Fun!