Given the following function f with two arguments, what is the standard way to apply map to only x?
A little discussion on currying and partial application
In FP terms, your function f
is "uncurried" - while it conceptually takes two arguments, they're bundled in a single product structure. In Python, everything is uncurried, all the time. You have to give all the arguments at once, or none of them.
To work around this, there are various tricks, but conceptually you just want to "curry" the function. That is, transform f(x,y)
into f(x)
which returns a new function g(y)
.
In languages which are curried by default , you can write this translation easily as:
-- curry: take a function from (x,y) to one from x to a function from y to z
curry :: ((x,y) -> z) -> (x -> y -> z)
curry f x y = f (x, y)
So curry
takes your curried f
and its product arguments, separately, and applies the arguments once they are all available. The opposite is also pretty easy:
uncurry :: (x -> y -> z) -> ((x,y) -> z)
uncurry f (x,y) = f x y
How does this relate to partial application?
- Currying takes a function that takes a structure of 1 (n-product) argument, and returns a new function taking n arguments.
- Partial application takes a function of n arguments and applies them to k arguments, yielding a function of n-k remaining arguments.
In an uncurried language, each of the arguments can be applied in turn (e.g. partially, with respect to the arity of the function). In a curried language, you have to play some tricks to uncurry the function first, as in the above examples.
I think it is more flexible to be in a curried-by-default environment, as partial application is free. In such an environment, it is common to chain together functions that modify a data structure into a pipeline. E.g. a pipeline of integer modifications:
(+1) . (*2) . (^3) $ 7
is just a chain of partially applied, uncurried functions, composed, each operating on the output of the previous function. This can be nice, as it separates concerns visually.