const id 1 2

posted on December 15, 2007 - tagged as: haskell

While playing around with the 99 problems in Haskell, I came across this function const that takes two arguments and returns the first without ever evaluating the second. For example:

const 1 2

returns 1. Now that is straightforward enough, but then I noticed that:

const id 1 2

returns 2, and, indeed const id x y always returns y. I was confused. id is the identity function and quite simply returns its argument untouched. After some searching and thinking, I realized how this works. If we consider the example above, it turns out that const id 1 discards the 1 and returns the id function. This function(id) is then evaluated with the remaining argument, 2, and, presto, we get 2 as the answer. Tricky, but not exactly readable. A more human friendly form is probably:

flip const 1 2

A simple description of the flip function is here. Hooray for first class functions and lazy evaluation!

Comments !

social

tags