我有以下代码:
def evAnd(v, *predicates):
satisfied=True
for f in predicates:
if not f(v):
satisfied=False
# log: f,v->False in a map and other side effects
else:
# log: f,v->True in a map and other side effects
return satisfied
def evOr(v, *predicates):
satisfied=False
for f in predicates:
if f(v):
satisfied=True
# log: f,v->True in a map and other side effects
else:
# log: f,v->False in a map and other side effects
return satisfied
在单个函数中统一上述内容的 Pythonic 方法是什么?(因为放置日志消息的地方有相当多的副作用代码)注意副作用的存在以及需要评估所有谓词的结果,而不会短路任何和所有
基于接受的答案的解决方案
所以,这就是我最终根据接受的答案所做的事情:
def adorn(predicate):
def rv(v):
rvi = predicate(v)
if rvi:
print "%s is satisfied for value %d" % (predicate.__name__, v)
# any other side effects
else:
print "%s is not satisfied for value %d" % (predicate.__name__, v)
# any other side effects
return rvi
return rv
def my_all(n, predicates):
return reduce(operator.and_, map( lambda x : x(n), map(adorn, predicates)), True)
def my_any(n, predicates):
return reduce(operator.or_, map( lambda x : x(n) , map(adorn, predicates)), False)
它可以通过以下方式进行测试:
def even(n):
return n%2==0
def odd(n):
return n%2!=0
print my_all(3, [even, odd])
print my_any(4, [even, odd])