Lambda Expressions and Higher-Order Functions 学习笔记和习题解答

CS61A Spring 笔记
参考: https://inst.eecs.berkeley.edu/~cs61a/sp18/lab/lab02/


Lambda Expressions

Lambda Expressions is one-line functions that specify two things: the parameters and the return expression.

lambda <parameters>: <return expression>

Differences between lambda and def :

differences

Higher Order Functions

A higher order function is a function that manipulates other functions by taking in functions as arguments, returning a function, or both.

Functions as arguments

using a def statement to create function:

def square(x):
    return x * x

The above statement created a function object with the intrinsic name square as well as binded it to the name square in the current environment.

A function that takes in another arguments:

def scale(f, x, k):
    """ Returns the result of f(x) scaled by k. """
    return k * f(x)

call scale on square and some other arguments:

>>> scale(square, 3, 2) # Double square(3)
18
>>> scale(square, 2, 5) # 5 times 2 squared
20

pass lambda functions into call expressions:

>>> scale(lambda x: x + 10, 5, 2)
30

Functions that return functions

Because functions are values, you can also return them in other functions!

def multiply_by(m):
    def multiply(n):
        return n * m
    return multiply
>>> multiply_by(3)
<function multiply_by.<locals>.multiply at ...>
>>> multiply(4)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'multiply' is not defined

We cannot directly call the inner function, two ways to call it:

>>> times_three = multiply_by(3) # Assign the result of the call expression to a name
>>> times_three(5) # Call the inner function with its new name
15
>>> multiply_by(3)(10) # Chain together two call expressions
30

Here’s what multiply_by would look like if we wrote it with a lambda expression:

def multiply_by(m):
    return lambda n: n * m

Environment Diagrams

Environment diagrams are one of the best learning tools for understanding lambda expressions and higher order functions because you’re able to keep track of all the different names, function objects, and arguments to functions.
Use Python tutor to draw Environment Diagrams.
for example:


Environment Diagrams

Questions:

What Would Python Display?

Q1: WWPD: Lambda the Free

(1)

>>> lambda x: x  # A lambda expression with one parameter x
______

>>> a = lambda x: x  # Assigning the lambda function to the name a
>>> a(5)
______

>>> (lambda: 3)()  # Using a lambda expression as an operator in a call exp.
______

>>> b = lambda x: lambda: x  # Lambdas can return other lambdas!
>>> c = b(88)
>>> c
______

>>> c()
______

>>> d = lambda f: f(4)  # They can have functions as arguments as well.
>>> def square(x):
...     return x * x
>>> d(square)
______
>>> lambda x: x  # A lambda expression with one parameter x
<function <lambda> at ...>

>>> a = lambda x: x  # Assigning the lambda function to the name a
>>> a(5)
5

>>> (lambda: 3)()  # Using a lambda expression as an operator in a call exp.
3
##
>>> b = lambda x: lambda: x  # Lambdas can return other lambdas!
>>> c = b(88)
>>> c
<function <lambda> at ...

>>> c()
88

>>> d = lambda f: f(4)  # They can have functions as arguments as well.
>>> def square(x):
...     return x * x
>>> d(square)
16

这里写图片描述

(2)

>>> z = 3
>>> e = lambda x: lambda y: lambda: x + y + z
>>> e(0)(1)()
______

>>> f = lambda z: x + z
>>> f(3)
______
>>> z = 3
>>> e = lambda x: lambda y: lambda: x + y + z
>>> e(0)(1)()
4

>>> f = lambda z: x + z
>>> f(3)
NameError: name 'x' is not defined

a2

(3)

>>> higher_order_lambda = lambda f: lambda x: f(x)
>>> g = lambda x: x * x
>>> higher_order_lambda(2)(g)  # Which argument belongs to which function call?
______

>>> higher_order_lambda(g)(2)
______

>>> call_thrice = lambda f: lambda x: f(f(f(x)))
>>> call_thrice(lambda y: y + 1)(0)
______

>>> print_lambda = lambda z: print(z)  
# When is the return expression of a lambda expression executed?
>>> print_lambda
______

>>> one_thousand = print_lambda(1000)
______

>>> one_thousand
______
>>> higher_order_lambda = lambda f: lambda x: f(x)
>>> g = lambda x: x * x
>>> higher_order_lambda(2)(g)  # Which argument belongs to which function call?
Error

>>> higher_order_lambda(g)(2)
4

>>> call_thrice = lambda f: lambda x: f(f(f(x)))
>>> call_thrice(lambda y: y + 1)(0)
3

>>> print_lambda = lambda z: print(z)  # When is the return expression of a lambda expression executed?
>>> print_lambda
Function

>>> one_thousand = print_lambda(1000)
1000

>>> one_thousand
# print_lambda returned None, so nothing gets displayed

q12

Q2: WWPD: Higher Order Functions

(1)

>>> def even(f):
...     def odd(x):
...         if x < 0:
...             return f(-x)
...         return f(x)
...     return odd
>>> steven = lambda x: x
>>> stewart = even(steven)
>>> stewart
______

>>> stewart(61)
______

>>> stewart(-4)
______
>>> def even(f):
...     def odd(x):
...         if x < 0:
...             return f(-x)
...         return f(x)
...     return odd
>>> steven = lambda x: x
>>> stewart = even(steven)
>>> stewart
<function ...> 

>>> stewart(61)
61

>>> stewart(-4)
4

https://goo.gl/ZQQAQd
A21

(2)

>>> def cake():
...    print('beets')
...    def pie():
...        print('sweets')
...        return 'cake'
...    return pie
>>> chocolate = cake()
______

>>> chocolate
______

>>> chocolate()
______

>>> more_chocolate, more_cake = chocolate(), cake
______

>>> more_chocolate
______

>>> def snake(x, y):
...    if cake == more_cake:
...        return lambda y: x + y
...    else:
...        return x + y
>>> snake(10, 20)
______

>>> snake(10, 20)(30)
______

>>> cake = 'cake'
>>> snake(10, 20)
______
>>> def cake():
...    print('beets')
...    def pie():
...        print('sweets')
...        return 'cake'
...    return pie
>>> chocolate = cake()
beets

>>> chocolate
Function

>>> chocolate()
sweets
'cake'

>>> more_chocolate, more_cake = chocolate(), cake
sweets

>>> more_chocolate
'cake'

>>> def snake(x, y):
...    if cake == more_cake:
...        return lambda y: x + y
...    else:
...        return x + y
>>> snake(10, 20)
Function

>>> snake(10, 20)(30)
40

>>> cake = 'cake'
>>> snake(10, 20)
30

https://goo.gl/FpWnBs
Q2A2

转载于:https://www.cnblogs.com/siucaan/p/9623180.html

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值