CS61A - Lin Growing

Lecture 5 · Environments

On this page

enviroments enable higher order funcitons

def make_adder(n):
	def adder(k):
		return k + n
	return adder
def apply_twice(f, x):
	return f(f(x))

def square(x):
	return x * x

result = apply_twice(square, 2)
## result = 16

An environment diagram for a higher-order functionTracing higher-order function calls in the environment model

lambda

square = lambda x: x * x
## 只能写return值, 并且只能一个表达式。因此,适合比较简单的function  
>>> square(4)
>>> 16
lambdadef
Both have the same domain, range, and behavior.
Both have the parent frame in which they were defined.
Both are bound to the name square.
After assignment, there is a reference to the function.Only def gives the function an intrinsic name.
Comparing lambda expressions and def statements

currying

  • Currying transforms a function of multiple arguments into a sequence of single-argument functions.
  • example:
  def curry2(f):
    def g(x):
      def h(y):
        return f(x,y)
      return h
    return g
## equivalente a : curry2 = lambda f: lambda x: lambda y: f(x, y)

English translation · Read Chinese original