?

Log in

No account? Create an account
haskell - Greg [entries|archive|friends|userinfo]
Greg

[ website | gregstoll.com ]
[ userinfo | livejournal userinfo ]
[ archive | journal archive ]

Links
[Links:| * Homepage * Mobile apps (Windows Phone, Win8, Android, webOS) * Pictures * LJBackup * Same-sex marriage map * iTunesAnalysis * Where's lunch? ]

haskell [Mar. 14th, 2007|08:09 am]
Greg
[Tags|, ]
[Current Mood |pensivepensive]

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...
LinkReply

Comments:
From: (Anonymous)
2007-03-14 12:47 pm (UTC)

interpreters and compilers

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

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

And on the command line:

$ runhaskell A.hs
26

Or compiled to native code:

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

Happy hacking!
(Reply) (Thread)
[User Picture]From: gregstoll
2007-03-14 12:56 pm (UTC)

Re: interpreters and compilers

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!
(Reply) (Parent) (Thread)