July 30, 2012

Not so lazy

In the Haskell programming language, lazy evaluation doesn't seem to be very lazy within list comprehensions. At least on my Ubuntu 12.4 system with its Haskell platform installed, it crashes after the following statement:
Prelude> [x*2 | x<-[0..], x<=5]
It shows the first five elements, but it doesn't return. I mean, it does after pushing Ctrl+C, but you may know that's the interrupt signal on Unix systems. It's not cool!

In its chapter about list comprehensions, the "Learn you a Haskell" textbook shows an example of a set comprehension from high school mathematics:
S = {2 · x | x ∈ N, x ≤ 10}
Then it goes on to say we can use [x*2 | x <- [1..10]] as the appropriate list comprehension. That's fine, but not exactly the stuff above. This wouldn't be an issue with any other programming language - even functional languages for that matter - but the Haskell community likes to take pride in the language being able to deal with infinite lists. For example, when I say take 10 [1..] , she doesn't try to completely evaluate the given list. She just gives you the first ten numbers. Because she's lazy. That's the point! This is why laziness is cool.

So why not write the list comprehension in a purely mathematical fashion, using the infinite list of natural numbers (which is [0..] ) instead?

Actually this is not a relevant issue, because I can define the comprehension with an infinite set and then use the take function to take a finite number of values from it. It works like a charm! The creators of haskell must have assumed that infinite lists will be used in comprehensions which are intended to be infinite as well, and no one will be such an asshole to print them out, even if the predicate makes the whole thing finite. Because it's just much simpler and more straightforward to use a finite range instead of limiting an infinite one with a predicate. But still it's a little bit uncool...

Programming languages should be asshole-proof!

1 comment:

hilda dada said...

Nice post. Thanks for sharing useful information. new york flood restoration