Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

the behavior of "const id"

Tags:

haskell

I'm working on the 99 Haskell questions and saw a solution for finding the last element of a list:

  myLast = foldr1 (const id) 

the type of const is a -> b -> a but that of const id is b -> a -> a
so what's the magic here?

like image 296
manuzhang Avatar asked Jan 05 '12 15:01

manuzhang


2 Answers

The type of id is c->c; it just returns the same thing it is given.

The type of const is a->b->a. In const id, a becomes c->c, so the type of const in this case becomes:

(c->c) -> b -> (c->c) 

Now that you have applied this const function, i.e. you have passed id to it, then you are left with b -> (c->c).

PS: The type of const const id is a->b->a, and the type of const const const id is b->a->a, and so on!

like image 119
Aaron McDaid Avatar answered Oct 11 '22 10:10

Aaron McDaid


No magic. The definition of const is:

const :: a -> b -> a const x y = x 

And the definition of id is:

id :: a -> a id x = x 

So const id is just \y -> id, a function that always returns id. And if id is just \x -> x then const id must be the same as \y -> \x -> x. Ergo, it has type b -> (a -> a).

const id can also be written flip const. Since const is \x -> \y -> x, then flip const takes the arguments in the opposite order, \y -> \x -> x, which is the same as const id.

like image 20
Apocalisp Avatar answered Oct 11 '22 11:10

Apocalisp