• The aim of this tutorial🔍 is to introduce anonymous/lambda functions in Python just to make sure they work in the Higher Order Functions lecture of SICP

1. syntax

Design and History FAQ — Python 3.9.1 documentation

  • restrictive
  • minimal
  • in python, lambdas are with anonymous functions
  • introduce it with lambda instead of def
lambda args: expression
  • multiple args
  • single expression

2. lambda as function expression

  • lambda can be assigned to a binding and thus have "name"
double = lambda x: x*2
print(double(5))
>>> 10
  • note that a vscode linter does rephrase this into a function declaration

3. usage

  • tiny in size
  • needed for a short time
  • possibly, the expression itself is more expressive than the name
  • usually, they are passed an argument for higher-order functions

4. example: lambdas in higher-order functions (HOF)

  • the HOF summationRecursive from SICP returns the same result for sumInt(a,b) as well as for sumIntLambda(a,b)
def summationRecursive(term, a, next, b):
if (a > b):
return 0
else:
return term(a) + summationRecursive(term, next(a), next, b)

""" proper function declarations """
def sumInt(a, b):
def _identity(x): return x
def _next(x): return x+1
return summationRecursive(_identity, a, _next, b)

""" using lambda functions """
def sumIntLambda(a,b):
return summationRecursive(lambda x: x, a, lambda x: x+1, b)

5. list used sources

Technical Support Engineer of Behavioural Data Platform (Snowplow Analytics). On comparison of programming languages, history of computing, and raw playbooks.