August 31, 2026

Haskell for Hobos -- Laziness -- and lists

Haskell is lazy. This seems like a strange thing to boast about. It has surprising advantages in various situations.

Haskell is all about procrastination. It doesn't compute anything until it absolutely has to. It sets up the machinery for performing computations, but sets them in motion only when actually needed.

lists

Lists are central to Haskell. This is a big part of why Haskell doesn't have "for" loops and such. Many (most?) computations are driven by processing a list. Square brackets are used to form a list:
mylist = [ 42, 123, 5 ]
Lists can contain any kind of thing, but the things must all have the same type. A range is often a handy way to form a list:
nextlist = [1..100]
And here is where laziness gets involved. You can define an infinite list:
biglist = [1..]
Then to print the 9th element of the list you use the "!!" operator to select the element you want.
main = putStrLn $ show $ biglist !! 9
So, what is with all the dollar signs. They are switching precedence from left associative to right associative. As an example, PutStrLn wants a single argument and will grab "show" and get upset because it is a function and not a string. With the dollar signs as shown, the "biglist !! 9" expression gets evaluated first, then things pass from right to left. This could all be accomplished with parenthesis, but things are much more readable with the dollar signs (once you get used to it) rather than a tangle of nested parenthesis.

list comprehensions

I like these. They are a way of generating a list that looks a lot like how sets are specified in mathematics. Here is an example:
evens = [ 2*x | x <- [1..100] ]
We can rely on Haskell laziness and write:
odds = [ 2*x+1 | x <- [0..] ]


Have any comments? Questions? Drop me a line!

Tom's software pages / tom@mmto.org