Haskell newbie here. I was going through Learn you a haskell, and came across this definition of the flip function.
flip' :: (a -> b -> c) -> (b -> a -> c)
flip' f = g
where g x y = f y x
What I don’t get is, where did x and y come from? I mean, the signature tells me that flip' is a function that takes a function (with two parameters), and returns a function (again, with two parameters).
If I’m understanding this right, when I write a function which goes like
foo :: (a -> b) -> a -> b
foo f x = f x -- applies the function f on x
But then, in this case I’m passing the parameter explicitly [ ie x ] and so I’m able to access it in the function body. So how come the flip' function can access the parameters x and y?
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.
The where clause allows for local definitions,
x=10ory="bla". You can also define functions locally with the same syntax you would for the top level.add x y = x + yIn the below equivalent formulation I make the substitution
g = f y xRight now g takes no parameters. But what if we defined g as
g a b = f b awell then we would have: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:
Cancel the y on each side for:
Now cancel the x:
and now to put it back in the full expression:
As a last cosmetic step we can make the substitution
atoxandbtoyto recover the function down to argument names: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
whereworks and how to do a little algebraic manipulation of Haskell code.