greynode » Haskell http://greynode.org ingĂ©nierie de tous les aspects de vie Fri, 15 Apr 2011 16:12:00 +0000 en hourly 1 http://wordpress.org/?v=3.1.1 Learning Haskell http://greynode.org/2009/05/17/9/ http://greynode.org/2009/05/17/9/#comments Mon, 18 May 2009 06:56:20 +0000 enum http://www.greynode.org/?p=9

Read the rest of this entry »

]]>
I have recently been continuing my journey with Haskell, the purely functional programming language. I had dabbled with it a little bit over the winter, but haven’t had much practice since then. It is my hope that over the summer I will be able to get a fair amount of practice with the language.

I have settled on using the book Real World Haskell as my first stepping stone. It has gotten good reviews, and was recommended to me by one of my professors. There is a free version of it online, if you wish to check it out. It uses quite a bit of comparison with imperative languages, at least in the early chapters, so I don’t recommend it to someone who has never programmed before.

For those of you who are not familiar with functional programming, I am going to present to you a few problems and the elegant solutions provided by Haskell. The first I will show you is an implementation of quicksort.

qsort (x:xs) = qsort (filter (< x) xs) ++ [x] ++ qsort (filter (>= x) xs)

This implementation of quicksort is so clean it makes me sick. It is essentially the definition of the quicksort algorithm. Because of the facilities provided by Haskell, it translates quite nicely.

Another problem I’d like to show you involves counting. Say you had a string of words, and you would like to count the number of words that start with an upper-case letter. In an imperative language, this might involve several loops and/or the use of regular expressions. With Haskell, its a simple matter of function composition. Have a look:

capCount = length . filter (isUpper . head) . words

This might look odd if you are not familiar with functional programming or function composition, but it is a really simple function. The ‘.’ operator simply takes the output from the function on the right, and feeds it into the function on the left. The ‘words’ function breaks a string up into a list of words wherever there is a space. The ‘head’ function returns the first element of the list, ‘isUpper’ will return a boolean value saying whether or not a Character is upper-case, ‘filter’ applies a function over a list and removes items that evaluate to False, and ‘length’ returns the length of the list. As you can see, it’s much easier to describe with code than with words.

Anyway, I will be posting anything I find interesting on here. Hopefully someone other than myself will benefit from it.

]]>
http://greynode.org/2009/05/17/9/feed/ 0