Lec 4 - High Order Functions
本页目录
- higher-order function is a funtion that takes a function as an argument or return value.
If and call expressions
- 调用表达式的真值判断能让我们表示出那些“不能表示的值”,而不至于导致函数报错
- 常规if写法
def real_sqrt(x):
### return the real part of the square root of x ###
if x >= 0:
return sqrt(x)
else:
return 0
- function写法
def if_(c, t, f):
if c:
return t
else:
return f
from math import sqrt
def real_sqrt(x):
return if_(x >= 0, sqrt(x), 0)
### 这里会先行evaluate () 内的函数,如果有错,则先于if_ 报错 ###
High order funtions
-
generalize the funtion
- assert 3 > 2, ‘Math is broken’
- 如果前面条件为假, 执行打印出后续error信息

-
generalize the math
- 优化前:

- generalize 后

- 优化前:
Funtions as return values
def make_adder(n):
def adder(k):
return k + n
return adder

