Elegance of Haskell

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 (n-1)!, to create the nth element of a new list. zipWith function exploits the basic property n!=n\cdot (n-1)!. Since we define a base case 0!=1 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 n (e.g. [0!,1!,\ldots,n!]), we use the take function with arguments n and fact. For example, if n=10, then

ghci> take 10 fact

This entry was posted in Haskell, Progamming and tagged , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s