首页 > 代码库 > 【codewar】Unary function chainer

【codewar】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. 

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

Should yield the same result as

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

## 思路分析:

返回值是由原参数构成的函数,解析成多层函数的嵌套。input 是内层的参数。

## 代码解析:

- Python

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

param 可是换成 result, 省略第三行(如下),不过不省略会语义上更清晰易读。注意 result 的作用域,别写成 for 的局部变量了

完整可运行代码如下:

 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 result12     return apply13 14 15 def f1(x): return x*216 17 18 def f2(x): return x+219 20 21 def f3(x): return x**222 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)*2

apply一开始的参数(result 的初始值)为 chained([f1, f2, f3])(0)中的0

【codewar】Unary function chainer