Sunday, September 29, 2013

How to generate UUID using Haskell - Part - 2

What is your favorite programming language?

Someone asked me this question about a month ago, suddenly I realized that, I can program in many languages, but I didn't know of a language that I am truly in love with.  At that time I was just starting to learn Haskell.

After about a month of hacking on Haskell, I am in a better position to answer this question.  Haskell is an awesome language and certainly is currently my favorite language!

I would like to ask this question to my readers:

Are you always 100% sure that, the code you have written will work without any problems, if it compiles OK?

Ever had to fix your own code because of NullPointerExceptions at run time?

With Haskell the mantra is:

If it compiles, it will work!

Over and above it, features delivered per lines of code ratio is extremely high with Haskell, i.e. more can be achieved by doing less!

I would say, learning Haskell is like falling in Love: It takes time, but once you are in it, its like the most beautiful thing :)

Alright, enough Haskell marketing, lets come back to the main topic of this post.  In the previous post we saw one approach to generate UUID's in Haskell using the system-uuid package, in this post we will look at yet another package that is well equipped to generate UUID's

How do they do it!

Haskell has a package called uuid that exposes a method to generate UUID values.  This package is a bit nicer than the system-uuid package since this package providers methods to convert UUID values to and from String values.

This package exposes methods like
  • toString - Converts UUID value to String value
  • fromString - Converts String value to UUID value
To install the uuid package use the following command
Next, generate the UUID value using this package are pretty straightforward:
  • The module Data.UUID.V1 has a method called nextUUID which will return us random UUID values, wrapped with IO monad (just like how system-uuid did)
  • However, this method also wraps the generated UUID value into the Maybe monad.
  • This is done to indicate that there is a possibility of failure while generating the UUID value.
  • Let's say because of some reason, if the UUID generation fails then, Nothing will be returned.
  • Maybe is an extremely elegant way to handle possibility of failure.
  • Once you have the UUID wrapped in Maybe and IO monad generated, you can extract the UUID value using the fromJust method
  • Let's see these steps in action, lets fire up the GHCI
This code snippet shows some extremely powerful feature of Haskell like Maybe and function composition.

That's all folks!  Till we meet again, Happy Hacking!
Have some Fun!