The Prelude, which is in the base package at hackage.haskell.org, is included with an implicit import in every Haskell file is where the flip function is found. On the right side you can click "source" and see the source code for flip.
flip :: (a -> b -> c) -> b -> a -> c
flip f x y = f y x
The where clause allows for local definitions, x=10
or y="bla"
. You can also define functions locally with the same syntax you would for the top level. add x y = x + y
In the below equivalent formulation I make the substitution g = f y x
flip :: (a -> b -> c) -> b -> a -> c
flip f x y = g
where
g = f y x
Right now g takes no parameters. But what if we defined g as g a b = f b a
well then we would have:
flip :: (a -> b -> c) -> b -> a -> c
flip f x y = g x y
where
g a b = f b a
No we can do a little algebraic cancelation(if you think of it like algebra from math class you will be pretty safe). Focusing in on:
flip f x y = g x y
Cancel the y on each side for:
flip f x = g x
Now cancel the x:
flip f = g
and now to put it back in the full expression:
flip :: (a -> b -> c) -> b -> a -> c
flip f = g
where
g a b = f b a
As a last cosmetic step we can make the substitution a
to x
and b
to y
to recover the function down to argument names:
flip :: (a -> b -> c) -> b -> a -> c
flip f = g
where
g x y = f y x
As you can see this definition of flip is a little round about and what we start with in the prelude is simple and is the definition I prefer. Hope that helps explain how where
works and how to do a little algebraic manipulation of Haskell code.
(a -> b) -> a -> b
and(a -> b) -> (a -> b)
are equivalent? – user824425a -> (b -> c)
asa -> b -> c
. – ersran9foo f x = f x
is the same asfoo f = f
(given the same type signature). Anyway, those parametersx
andy
you mention are bound in the definition ofg
, that's where they come from. The definition ofg
can also be written asg = (\x y -> f y x)
. This means thatflip'
could also be defined asflip' f = (\x y -> f y x)
, which is equivalent toflip' f x y = f y x
. This is in a way related to the right-associativity of(->)
. – user824425