【codewar-7kyu】Unary function chainer

## 題目描述:

Your task is to write a higher order function for chaining together a list of unary functions. In other words, it should return a function that does a left fold on the given functions. python

chained([a,b,c,d])(input)

Should yield the same result asapp

d(c(b(a(input))))

## 思路分析:

返回值是由原參數構成的函數,解析成多層函數的嵌套。input 是內層的參數。函數

## 代碼解析:

- Python

1 def chained(functions):
2     def apply(param):
3         result = param
4         for f in functions:
5             result = f(result)
6         return result
7     return apply

param 但是換成 result, 省略第三行(以下),不過不省略會語義上更清晰易讀。注意 result 的做用域,別寫成 for 的局部變量了spa

完整可運行代碼以下:code

 1 #!/usr/bin/python
 2 # -*- coding: utf-8 -*-
 3 
 4 __author__ = 'pudding'
 5 
 6 
 7 def chained(functions):
 8     def apply(result):
 9         for f in functions:
10             result = f(result)
11         return result
12     return apply
13 
14 
15 def f1(x): return x*2
16 
17 
18 def f2(x): return x+2
19 
20 
21 def f3(x): return x**2
22 
23 def f4(x): return x.split()
24 
25 
26 def f5(xs): return [x[::-1].title() for x in xs]
27 
28 
29 def f6(xs): return "_".join(xs)
30 
31 
32 if __name__ == '__main__':
33     print chained([f1, f2, f3])(0)

輸出結果:4 即:((0**2)+2)*2blog

apply一開始的參數(result 的初始值)爲 chained([f1, f2, f3])(0)中的0utf-8

必定要注意 return apply 而不是 return apply()作用域

相關文章
相關標籤/搜索