Mood: pensive
Posted on 2007-03-14 08:09:00
Tags: haskell programming
Words: 289

So it's been a little while since I've learned a new language, and I keep hearing rumblings about Haskell (programming.reddit.com really loves it). So I started to read A Gentle Introduction to Haskell, and...wow. I haven't done deep functional stuff since college, and I made it about halfway through before my brain up and revolted.

It has a lot of neat features that you would expect in a functional language, and it has the neat Prologish way of defining functions by pattern matching. For example, here's my first Haskell program!

leng [] = 0
leng (_:xs) = 1 + leng xs

main = print (leng ['a','b','c'])

This is defining a function leng ("length" is built in to the standard library) that returns the length of a list. Note that you don't say what to do to calculate the length, exactly, you specify that the length of an empty list is 0, and the length of any other list is 1 plus the length of the rest of the list.

It took me a while to figure out the exact syntax to define this, but I finally did and compiled it with the Glasgow Haskell Compiler (ghc). It took 6 seconds, which seems like a really long time for something so simple. Maybe there's a fixed amount of overhead or something. And the resulting executable was 370KB!! I'm guessing this is because it compiles it to a binary executable, which I wasn't expecting, so you don't get the benefit of an interpreter. It runs instantly, as you would expect.

Anyway, I'll keep reading and thinking what would be a good project to do in it. I/O looked weird, but that was about when my brain shut down yesterday so maybe I'll start there today...


Comment from anonymous:

You also get a bytecode interpreter with GHC, namely GHCi. Assuming your source is in A.hs:

$ ghci A.hs
*Main> main
*Main> :t leng
leng :: (Num t1) => [t] -> t1
*Main> leng [1..10]
*Main> leng "haskell"

And on the command line:

$ runhaskell A.hs

Or compiled to native code:

$ ghc -O A.hs
$ ./a.out

Happy hacking!

Comment from gregstoll:

Ahh, neat! I played around with ghci for a bit but got frustrated when I couldn't figure out how to define anything (I kept trying to explicitly type it, and then there were some syntax issues). Thanks!

This backup was done by LJBackup.