尽管python不是纯函数编程语言,lambda语法很不友好,但它是门多范式语言,可以方便进行扩展(如fn、pymonad、hylang),这里主要介绍fn。
fn是个python的函数式编程(Functional Programming, FP)库,极大方便了python fp。
(本准备写个教程,发现官方文档写得很详细…以下内容从 https://github/kachayev/fn.py搬运。)
1. lambda定义(“-“)
from fn import _
print (_ + 2) # "(x1) => (x1 + 2)"
print (_ + _ * _) # "(x1, x2, x3) => (x1 + (x2 * x3))"
2. lazy-seq (“Stream”)
Stream用于创建情性序列,和itertor很像,常常用于定义无穷序列。
from fn import Stream
s = Stream() << range(6) << [6,7]
assert list(s) == [0,1,2,3,4,5,6,7]
f = Stream()
fib = f << [0, 1] << map(add, f, drop(1, f))
# 创建fib无穷序列
assert list(take(10, fib)) == [0,1,1,2,3,5,8,13,21,34]
assert fib[20] == 6765
assert list(fib[30:35]) == [832040,1346269,2178309,3524578,5702887]
3. curring(柯里化)
from fn.func import curried
@curried
def sum5(a, b, c, d, e):
return a + b + c + d + e
assert sum5(1)(2)(3)(4)(5) == sum5(1, 2, 3)(4, 5)
assert sum5(1)(2)(3)(4)(5) == sum5(1, 2, 3, 4, 5)
4. 高级函数操作(F)
fn.F
用于包装并构造复杂函数
from fn import F, _
from fn.iters import filter, range
# 类似管道操作
func = F() >> (filter, _ < 6) >> sum
assert func(range(10)) == 15
最后,附图,使用fp实现dict
STOP WRITING CLASSES!!
更多推荐
Python函数式编程(fn)
发布评论