Python Currying Function (With Examples)

In this tutorial, we will learn about the currying function with the help of examples. By Yash Khandelwal Last updated : December 30, 2023

What is Currying?

In terms of Mathematics and Computer science, currying is the approach/technique by which we can break multiple-argument function to single argument function.

Mathematical illustration: h(x)=g(f(x))

The composition of two functions is a chaining process in which the output becomes the input for the outer function.

def currying( g , f ):
    def h(x):
        return g(f(x))
    return h

Python Currying Function

In the technical term "Currying is the process of transforming a function that takes 'n' arguments into a series of 'n' function that only takes the one argument each."

In problem-solving approach, currying is to be done to simplify the programming i.e. execution of the function which takes multiple arguments into the single - single argument functions.

Python Currying Function Examples

Practice these examples to learn the concept of currying functions in Python.

Example 1

def f(a):
    def g(b, c, d, e):
        print(a, b, c, d, e)
    return g #as in f it return g this is currying
 
f1 = f(1)

f1(2,3,4,5)

Output

1 2 3 4 5

Explanation

Now, f(1) returns the function g(b, c, d, e) which, for all b, c, d, and e, behaves exactly like f(1, b, c, d, e). Since g is a function, it should support currying as well.

Example 2

def f(a):
    def g(b):
        def h(c):
            def i(d):
                def j(e):
                    print(a, b, c, d, e)
                return j  #return to function i
            return i      #return to function h
        return h          #return to function g
    return g              #return to function f
 
f(1)(2)(3)(4)(5)

Output

1 2 3 4 5

Explanation

In the code we have, X(a,b,c,d,e) = f(g(h(i(j(a,b,c,d,e))))

Here, the concept is of nesting of one function to another and hence the result of one function get stored or recorded in another function as a chain of functions.

Note: Now f(a,b,c,d,e) is no more i.e. now f no more take 5 arguments.

Example 3

Python example of currying function to convert INR to pounds

# program to covert the Indian Rupee to Pound
# Demonstrating  Currying of composition of function
def change(b, c): 
    def a(x): #by currying function
        return b(c(x)) 
    return a 
      
def IR2USD(ammount):  
    return ammount*0.014  # as 1IR=0.014USD
      
def USD2Pound(ammount):  # Function converting USD to Pounds 
    return ammount * 0.77 
      
if __name__ == '__main__': 
    Convert = change(IR2USD,USD2Pound )
    
    e = Convert(565)
    print("Conveted Indian Rupee to Pound:")
    print('565 INDIAN RUPEES =',e,'PoundSterling')      

Output

Conveted Indian Rupee to Pound:
565 INDIAN RUPEES = 6.0907 PoundSterling

Python Tutorial

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.