Skip to content

Commit ea59b38

Browse files
committed
add high_order_func.md
1 parent 76763bb commit ea59b38

1 file changed

Lines changed: 29 additions & 0 deletions

File tree

Functional/high_order_func.md

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,31 @@
11
# 高阶函数
22

3+
在函数式编程中,我们可以将函数当作变量一样自由使用。一个函数接收另一个函数作为参数,这种函数称之为**高阶函数(Higher-order Functions)**
4+
5+
看一个简单的例子:
6+
7+
```python
8+
def func(g, arr):
9+
return [g(x) for x in arr]
10+
```
11+
12+
上面的代码中,`func` 是一个高阶函数,它接收两个参数,第 1 个参数是函数,第 2 个参数是数组,`func` 的功能是将函数 g 逐个作用于数组 arr 上,并返回一个新的数组,比如,我们可以这样用:
13+
14+
```
15+
def double(x):
16+
return 2 * x
17+
18+
def square(x):
19+
return x * x
20+
21+
arr1 = func(double, [1, 2, 3, 4])
22+
arr2 = func(square, [1, 2, 3, 4])
23+
```
24+
25+
不难判断出,arr1 是 [2, 4, 6, 8],arr2 是 [1, 4, 9, 16]
26+
27+
# 小结
28+
29+
- 可接收其他函数作为参数的函数称为高阶函数。
30+
31+

0 commit comments

Comments
 (0)