Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Haskell's "flip id" has this type?

Tags:

haskell

I'm curious about the expression flip id (It's not homework: I found it in the getOpt documentation).

I wonder why it has this type:

Prelude> :t (flip id) (flip id) :: b -> (b -> c) -> c 

For example, (flip id) 5 (+6) gives 11.

I know why id (+6) 5 gives 11, but I don't "get" the flip id thing.

I tried to figure this out myself using pen and paper but couldn't. Could anybody please explain this to me? I mean, how does flip id come to have the type b -> (b -> c) -> c ?

like image 228
Niccolo M. Avatar asked Sep 09 '12 14:09

Niccolo M.


1 Answers

The id function has this type:

id :: a -> a 

You get an instance of this type, when you replace a by a -> b:

id :: (a -> b) -> (a -> b) 

which, because of currying, is the same as:

id :: (a -> b) -> a -> b 

Now apply flip to this and you get:

flip id :: a -> (a -> b) -> b 

In the case of id (+) the instance is:

id :: (Num a) => (a -> a) -> (a -> a) 

Now flip id gives you:

flip id :: (Num a) => a -> (a -> a) -> a 

Side note: This also shows you how ($) is the same as id, just with a more restricted type:

($) :: (a -> b) -> a -> b ($) f x = f x -- unpoint: ($) f   = f -- hence: ($)     = id 
like image 174
ertes Avatar answered Sep 23 '22 19:09

ertes