Thanks to lazy evaluation, a Haskell program doesn't (almost can't) do what it looks like it does.
Consider this program:
main = putStrLn (show (quicksort [8, 6, 7, 5, 3, 0, 9]))
In an eager language, first quicksort
would run, then show
, then putStrLn
. A function's arguments are computed before that function starts running.
In Haskell, it's the opposite. The function starts running first. The arguments are only computed when the function actually uses them. And a compound argument, like a list, is computed one piece at a time, as each piece of it is used.
So the first thing that happens in this program is that putStrLn
starts running.
GHC's implementation of putStrLn
works by copying the characters of the argument String into to an output buffer. But when it enters this loop, show
has not run yet. Therefore, when it goes to copy the first character from the string, Haskell evaluates the fraction of the show
and quicksort
calls needed to compute that character. Then putStrLn
moves on to the next character. So the execution of all three functions—putStrLn
, show
, and quicksort
— is interleaved. quicksort
executes incrementally, leaving a graph of unevaluated thunks as it goes to remember where it left off.
Now this is wildly different from what you might expect if you're familiar with, you know, any other programming language ever. It's not easy to visualize how quicksort
actually behaves in Haskell in terms of memory accesses or even the order of comparisons. If you could only observe the behavior, and not the source code, you would not recognize what it's doing as a quicksort.
For example, the C version of quicksort partitions all the data before the first recursive call. In the Haskell version, the first element of the result will be computed (and could even appear on your screen) before the first partition is finished running—indeed before any work at all is done on greater
.
P.S. The Haskell code would be more quicksort-like if it did the same number of comparisons as quicksort; the code as written does twice as many comparisons because lesser
and greater
are specified to be computed independently, doing two linear scans through the list. Of course it's possible in principle for the compiler to be smart enough to eliminate the extra comparisons; or the code could be changed to use Data.List.partition
.
P.P.S. The classic example of Haskell algorithms turning out not to behave how you expected is the sieve of Eratosthenes for computing primes.
O(N^2)
runtime.