February 14, 2010

Introduction to Haskell and Erlang

I am reading Masterminds of Programming, by O'Reilly. It is a very good book I will get back to in other posts. Reading up on the thoughts of Haskell core language developers made me very interested in the language and functional programming in general. Haskell and Erlang are functional languages, so it takes a while to get into the mindset but seems like it's all worth the while.

I looked up some Haskell resources: http://www.haskell.org/haskellwiki/Haskell_in_5_steps

Then I saw the Haskell "Hello World"

Prelude> "Hello, World!"
"Hello, World!"
And immediately fell in love. Is there a simpler way to say "Hello, World!"?

This Haskell hacking video is also a great source of inspiration :)

There is also a nice guidebook called Learn You a Haskell for Great Good! with cutesy pictures and writing that takes you by the hand. Very nice. Reminds me of the Poignant Guide to Ruby. :) Erlang has got another one named Learn You Some Erlang for Great Good!, and you can't go wrong with one that has got a bearded squid on the cover =D

Erlang indeed looks to be a very nice language. This is an example from the book:

1> Weather = [
  {toronto, rain},
  {montreal, storms},
  {london, fog},
  {paris, sun},
  {boston, fog},
  {vancouver, snow}].

2> FoggyPlaces = [X || {X, fog} <- Weather].

In fact this is even more compact syntax than in Ruby. Erlang atoms behave much in the same way as Ruby symbols. In which the equivalent would be something like:

>> weather = [
  {'Toronto' => :rain},
  {'Montreal' => :storms},
  {'London' => :fog},
  {'Paris' => :sun},
  {'Boston' => :fog},
  {'Vancouver' => :snow}]

>> foggy_places = weather.collect{|x| x.keys[0] if x.values[0]==:fog }.compact
=> ["London", "Boston"]
>> foggy_places = weather.select{|x| x.values[0]==:fog }.collect(&:keys).flatten
=> ["London", "Boston"]

Either case, I cannot think of a better way to say this in Ruby and Erlang has a cleaner way.

Joe Armstrong is one of the original Ericsson engineers who designed Erlang and wrote the first implementation. He describes using Erlang to feed data onto the page by web sockets. I am completely astonished. I need dig deeper into this...