Created
November 7, 2013 13:31
-
-
Save rvantonder/7354596 to your computer and use it in GitHub Desktop.
This sprung from wanting to know the difference between currying and partial function application in the functional programming paradigm. An example in Python.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Consider the function f, with arity 3: | |
f = lambda x,y,z: x+y+z | |
# Let's curry f: | |
f_curried = lambda x: lambda y: lambda z: x+y+z | |
# f_curried has arity 1. When called with an argument, it will | |
# return another function (say, g) of arity 1 down the chain, e.g.: | |
g = f_curried(1) | |
# It may seem like we 'fixed' one argument, and can perform partial | |
# function application. In order for that to be true, we should | |
# be able to do this: | |
g(2,3) # which will not work since g has arity 1 | |
# if we wanted to evaluate the sum of 3 integers using f, we would | |
# do so as follows: | |
f_curried(1)(2)(3) | |
# To perform partial function application by fixing x, our f | |
# would look like this: | |
f_partial = lambda x: lambda y,z: x+y+z | |
# x is fixed and we have g_partial with arity 2 | |
g_partial = f_partial(1) | |
# True partial function application can be performed on g_partial: | |
g_partial(2,3) | |
# To perform partial function application by fixing x and y, our f | |
# would look like this: | |
f_partial = lambda x,y: lambda z: x+y+z | |
g_partial = f_partial(1,2) | |
g_partial(3) | |
# there is a module in python called functools, with a function partial | |
import partial from functools | |
# You specify which arguments you want fixed, and partial returns the appropriate function | |
# Let's take our original function | |
f = lambda x,y,z: x+y+z | |
f_partial = partial(f,1) | |
f_partial(2,3) | |
# So the partial from functools transforms f = lambda x,y,z: x+y+z -> f = lambda x: lambda y,z: x+y+z | |
#Similarly | |
f_partial = partial(f,2,3) | |
f_partial(1) | |
# Was transformed from f = lambda x,y,z: x+y+z -> f = lambda x,y: lambda z: x+y+z |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment