public
Created

This sprung from wanting to know the difference between currying and partial function application in the functional programming paradigm. An example in Python.

  • Download Gist
example.py
Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
# 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

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.