Lambda Functions in Python

 

Kelly Chang

@rasca0027

kelly.chang@nyu.edu

 

Where did lambda come from?

  • Lambda Calculus, Alonzo Church, 1936
(\lambda x. x + x) 3 = 3 + 3 = 6
(λx.x+x)3=3+3=6 (\lambda x. x + x) 3 = 3 + 3 = 6
(\lambda x. x + 1) y = [y/x] x + 1 = y + 1
(λx.x+1)y=[y/x]x+1=y+1 (\lambda x. x + 1) y = [y/x] x + 1 = y + 1

Turing Complete:

it is a universal model of computation that can be used to simulate any Turing machine

(\lambda x. x y)(\lambda z.z)
(λx.xy)(λz.z)(\lambda x. x y)(\lambda z.z)
= ([(\lambda z.z)/x]. (x y))
=([(λz.z)/x].(xy))= ([(\lambda z.z)/x]. (x y))
= (\lambda z.z) y
=(λz.z)y= (\lambda z.z) y
= [y/z] z
=[y/z]z= [y/z] z
= y
=y= y

Lambda Functions

Also called: Anonymous function

 

  • Functions as first-class citizens
  • Often used as arguments in
    higher-order functions
def addition(a, b):
    return a + b

>>> addition(1, 3)
>>> 4

add = lambda a, b: a + b

>>> add(1, 2)
>>> 3 


MAP

map(function, sequence)

def plus(x): 
    return x + 1
map(plus, range(3))
>>> [1, 2, 3]

map(lambda x: x + 1, range(3))
>>> [1, 2, 3]

FILTER

def f(x):
    return x % 2 == 0
filter(f, range(10))
>>> [0, 2, 4, 6, 8]

filter(lambda x: x % 2 == 0, range(10))
>>> [0, 2, 4, 6, 8]

price = '3,450 元'
filter(lambda x: x.isdigit(), price)
>>> 3450

filter(function, sequence)

Higher-Order Functions

Currying Functions

Currying

 "The technique of transforming a function that takes multiple arguments in such a way that it can be called as a chain of functions each with a single argument"

h(x) = g(f(x)) = (g.f)(x)
h(x)=g(f(x))=(g.f)(x)h(x) = g(f(x)) = (g.f)(x)
def comp(threshold):
    return lambda x: x < threshold

>>> comp
<function comp at 0x10703e048>
>>> comp(10)
<function comp.<locals>.<lambda> at 0x10703e1e0>
>>> f = comp(10)
>>> f(1)
True

>>> func_a = comp(10)
>>> func_b = comp(20)

>>> print(func_a(5), func_a(8), func_a(13), func_a(21))
True True False False

Turn a function into curried function

with functools and lambda

def add(x, y):
    return x + y

add(5)
>>> Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    TypeError: add() takes exactly 2 arguments (1 given)

# try using functool
from functools import partial
f = partial(add, y=3)
f(2)
>>> 5

# using lambda
def example(a, b, c):
  return (a, b, c)
  
curried1 = lambda b, c: example(1, b, c)
curried1(2, 3)
>>> (1, 2, 3)

Reference

  • http://kachayev.github.io/talks/uapycon2012/
  • Haskell趣學指南
  • FLOLAC 2015
  • http://www.jianshu.com/p/81b12f4eae3a
  • https://www.python-course.eu/currying_in_python.php
  • https://mtomassoli.wordpress.com/2012/03/18/currying-in-python/
  • https://www.inf.fu-berlin.de/lehre/WS03/alpi/lambda.pdf
  • https://safalra.com/lambda-calculus/
  •  

Lambda in Python

By Kelly Chang

Lambda in Python

Explaining Lambda Functions in Python

  • 632