码迷,mamicode.com
首页 > 其他好文 > 详细

【codewar】Unary function chainer

时间:2016-08-30 01:43:34      阅读:234      评论:0      收藏:0      [点我收藏+]

标签:

## 题目描述:

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 = param
4         for f in functions:
5             result = f(result)
6         return result
7     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 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)*2

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

【codewar】Unary function chainer

标签:

原文地址:http://www.cnblogs.com/pudding-ai/p/5820254.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!