- 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
Unlike lambda forms in other languages, where they add functionality, Python lambdas are only a shorthand notation if you’re too lazy to define a function.
- in python, lambdas are synonymous with anonymous functions
- introduce it with
lambda args: expression
- single expression
2. lambda as function expression
lambdacan be assigned to a binding and thus have "name"
double = lambda x: x*2
- note that a vscode linter does rephrase this into a function declaration
- 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
summationRecursivefrom SICP returns the same result for
sumInt(a,b)as well as for
def summationRecursive(term, a, next, b):
if (a > b):
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 """
return summationRecursive(lambda x: x, a, lambda x: x+1, b)