Learning Myself a Haskell for Great Good

For years, I’ve wanted to learn more about functional programming.  It’s a very different method of providing solutions to problems (which, after all, is all programming is about, in the most generic sense possible).  Now that things have calmed down a bit in the rest of my life, I’m making a concerted effort to understand it.  After talking with Franklin Chen, he recommend Learn You a Haskell for Great Good.

I just started today – it was very simple to download the Haskell platform and get it up and running on my Mac Air (although if you don’t already have Xcode installed, it may be a little more difficult and/or time-consuming).  Run the installer, open a terminal, type ghci, and you should be good to go.

I spent a few easy hours this morning setting up and going over the first part.  List semantics were relatively straightforward (e.g., head and tail instead of the car and cdr I vaguely remember from my one undergrad class in Lisp).  My first a-ha moment (the whole reason I’m doing this exercise in learning Haskell is to maximize the number of a-ha moments) was the section on list comprehensions.  If you’re familiar with set theory, this is just like set comprehensions: describe what a set should contain, and the set just kind of has it.  In Haskell, replace sets with lists, but for simple purposes, you can ignore that.  For example, let’s say you wanted the set of all positive integers less than 10.  In the GHCI (the Haskell REPL), just type:

[x | x <- [1..9]]

and you get…

*Main> [x | x <- [1..9]]
[1,2,3,4,5,6,7,8,9]

But let’s say you wanted only the ODD numbers less than 10.  Just add a filter (in math-speak, a predicate):

[x | x <- [1..9], odd x]

…and you get:

*Main> [x | x <- [1..9], odd x]
[1,3,5,7,9]

Cool!  You can arbitrarily add predicates easily, as well.

*Main> [x | x <- [1..9], odd x, x > 5]
[7,9]

Super-cool!

You can do this in Ruby, as well, but it seems much more a fundamental part of Haskell.  That’s why people say that learning a functional language can help you in the other languages you program in.  I’m looking forward to more a-ha moments as I go on.

Also, the number one improvement idea I got from my Sentiment Analysis talk was “quit using Komodo Edit”, so I’m forcing myself to do everything with Aquamacs now.

 

Comments are closed.