# [python]初探’函数式编程’

hanoi(n) :- dohanoi(n, ‘a’, ‘b’, ‘c’).
dohanoi(0, _ , _ , _ ) :- !.
dohanoi(n, a, b, c) :-
n1 is n-1,
dohanoi(n1, a, c, b),
writeln([move, n, a–>c]),
dohanoi(n1, b, a, c).

>>> min(1, 2)
1
>>> f = min
>>> f(1, 2)
1
>>> f

>>> min

>>> min = 10
>>> min(1, 2)
traceback (most recent call last):
file “”, line 1, in
typeerror: ‘int’ object is not callable
>>> f(1, 2)
1
>>> min = f
>>> min(1, 2)
1

… return a+b

>>> def mysum(f, *l):
… a = 0
… for i in l:
… a = f(a, i)
… return a

6
>>> mysum(add, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
55

map/reduce

map(f, [x1, x2, …, xn]) = [f(x1), f(x2), …, f(xn)]

reduce(f, [x1, x2, x3, x4]) = f(f(f(x1, x2), x3), x4)

filter

filter 和 map 函数类似，接受一个函数和 iterable，返回也是一个 list，不过其功能是根据函数返回值是否为 true 来判断是否保留该值。例如：

def is_odd(n):
return n % 2 == 1
list(filter(is_odd, [1, 2, 4, 5, 6, 9, 10, 15]))
# 结果: [1, 5, 9, 15]sorted

sorted 函数同样是一个高阶函数，对参数 key 传递函数可以将需要排列的序列经过 key 函数处理后再进行排序，不过不会改变序列的值，例如：

>>> sorted([36, 5, -12, 9, -21], key=abs)
[5, 9, -12, -21, 36]装饰器(decorator)

import logging
def log(func):
def wrapper(*args, **kw):
logging.warn(“%s is running” % func.__name__)
func(*args, **kw)
return wrapper

def f():
print(“in function f”)
f = log(f)

>>> f()
warning:root:f is running
in function f

@log
def f():
print(“in function f”)含参数的装饰器

import logging
def log(level):
def decorator(func):
def wrapper(*args, **kw):
logging.warn(“%s is running at level %d” % (func.__name__, level))
return func(*args, **kw)
return wrapper
return decorator
@log(2)
def f():
print(“in function f”)
>>> f()
warning:root:f is running at level 2
in function f进一步理解

#对于不加装饰器的 f，其 name 不变
>>> def f():
… print(“in function f”)

>>> f.__name__
‘f’
#对于添加装饰器的函数，其 name 改变了
>>> @log
… def f():
… print(“in function f”)

>>> f.__name__
‘wrapper’

import functools
import logging
def log(func):
functools.wraps(func)
def wrapper(*args, **kw):
logging.warn(“%s is running” % func.__name__)
func(*args, **kw)
return wrapper
>>> @log
… def f():
… print(“in function f”)

>>> f.__name__
‘f’

@a
@b
@c
def f ():
# 等价于
f = a(b(c(f)))总结

Posted in 未分类