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?
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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With