I started learning Haskell after reading about the programming language in the answers to the MathOverflow question “What programming languages do mathematicians use?” Its alleged elegance sold me on the language. Although I’ve barely gotten my feet wet, I am already impressed with Haskell. I want to share an example of its elegance with you today.
Haskell’s lazy evaluation allows us to create infinite data structures, such as infinite lists. Haskell also allows for circular references; we can reference a function in its own definition in a way that is not explicitly recursive. Using this freedom, we can create an infinite list of factorials with just two lines of code, one of which is a type declaration.
fact :: [Integer]
fact = 1:(zipWith (*) fact [1..])
The nth iteration of the zipWith function multiplies the nth element of the positive integers (1..n) by the nth element of the list fact, which is , to create the nth element of a new list. zipWith function exploits the basic property . Since we define a base case by prepending a 1 to the list returned by zipWith , we see that the recursion is well-defined.
To obtain a list of just the factorials up to some nonnegative integer (e.g. ), we use the take function with arguments and fact. For example, if , then
ghci> take 10 fact