决定梳理这个内容是因为一个课程,
index.html
文件拖到浏览器,然后方向键下键,ppt以网页形式播放)大致意思就是,让函数也成为可以传递的参数,是python的一种编程思想。
下面直接举例子说明:
def map(fn):
"""
Higher-order map. 高阶函数
See ``_
Args:
fn (one-arg function): Function from one value to one value.
Returns:
function : A function that takes a list, applies `fn` to each element, and returns a
new list
"""
# TODO: Implement for Task 0.3.
def _map(ls):
return [fn(x) for x in ls]
return _map
def neg(x):
return -x
def negList(ls):
"Use :func:`map` and :func:`neg` to negate each element in `ls`"
return map(neg)(ls)
可以看到,
map
函数本身只有一个参数,就是传入一个函数,map
函数中定义了另一个函数,其有一个参数用来传递数据,同时该函数中进行了数据处理的工作,最终返回的是一个函数。map
中传入一个参数,为函数名称,同时由于返回对象是一个函数,所以后面的括号(ls)
实际上就是传入给返回的函数的参数。类似的例子如:
zip
函数
def zipWith(fn):
"""
Higher-order zipwith (or map2).
.. image:: figs/Ops/ziplist.png
See ``_
Args:
fn (two-arg function): combine two values
Returns:
function : takes two equally sized lists `ls1` and `ls2`, produce a new list by
applying fn(x, y) on each pair of elements.
"""
# TODO: Implement for Task 0.3.
def _zip(ls1, ls2):
# return [fn(x,y) for x,y in zip(ls1,ls2)]
res = []
for i in range(len(ls1)):
res.append(fn(ls1[i], ls2[i]))
return res
return _zip
def addLists(ls1, ls2):
"Add the elements of `ls1` and `ls2` using :func:`zipWith` and :func:`add`"
return zipWith(add)(ls1, ls2)
reduce
函数
def reduce(fn, start):
r"""
Higher-order reduce.
.. image:: figs/Ops/reducelist.png
Args:
fn (two-arg function): combine two values
start (float): start value :math:`x_0`
Returns:
function : function that takes a list `ls` of elements
:math:`x_1 \ldots x_n` and computes the reduction :math:`fn(x_3, fn(x_2,
fn(x_1, x_0)))`
"""
# TODO: Implement for Task 0.3.
def _reduce(ls, start=start):
if not ls:
return start
start = fn(start, ls[0])
return _reduce(ls[1:], start)
return _reduce
def sum(ls):
"Sum up a list using :func:`reduce` and :func:`add`."
# TODO: Implement for Task 0.3.
return reduce(add, 0.0)(ls)
参考:
minitorch/slides-master/docs/slides+build2/module0.1.html#/28
函数式编程:
minitorch/slides-master/docs/slides+build2/module0.1.html#/29
函数式编程,使用函数作为参数,如上所示
minitorch/slides-master/docs/slides+build2/module0.1.html#/30
minitorch/slides-master/docs/slides+build2/module0.1.html#/31
Higher-order Filter(高阶函数/过滤器)
minitorch/slides-master/docs/slides+build2/module0.1.html#/35/0/2