Home CS61A: Function Currying
Post
Cancel

CS61A: Function Currying

Function Currying

  • We manipulate functions such that instead of posessing multiple arguments, they become a higher order function that accepts a single argument and returns other functions to proess the other arguments.
1
2
3
4
5
6
7
8
9
10
11
12
from operator import add

def curry2(f):
    def g(x):
        def h(y):
            return f(x, y)
        return h
    return g

adder = curry2(add)
add_three = adder(3)
add_three(4)
1
7
  • The curried function curry2 can also be expressed as a nested lambda function.
1
2
3
curry2 = lambda f: lambda x: lambda y: f(x, y)
adder = curry2(add)
adder(3)(4)
1
7
This post is licensed under CC BY 4.0 by the author.

CS61A: Lambda Expressions

CS61A: Lecture 5