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!
Reading your post alone, I cannot tell why either of these expressions is useful or sensical.
Have you seen Project Euler? It looks like an interesting way to brush up on algorithms in a fun way.
It really isn’t all that useful. They were using the function with a foldr to get the last element in the list.
I was thinking about the same and figured out that it’s synonymous to (flip const), without realizing how it actually works. Which makes me feel stupid, because now it seems like it should have been obvious.
In fact, it actually amounts to raping binding precedence and const’s type a -> b -> a. It takes two arguments, ignores the third and interprets id of type a -> a as the first, which it subsequently preserves, discarding the second, as you said.
const id 1 2
(const id 1) 2
id 2 => 2
I guess I learned something. Thanks. Heh.