本文介绍了函数式编程 - for和while循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图在和中写,而在Python中写循环 - 函数式编程风格。
I'm trying to write for and while loops in Python — functional programming style.
我认为对于结构很好,但是,而不起作用,它无限运行。
I think for construct is fine, but while doesn't work, it runs infinitely.
# for loop lst = [1, 2, 3] def fun(e): return e print map(fun, lst) # while loop i = 1 def whileloop(): global i print i i = i+1 while_FP = lambda: ((i < 5) and whileloop()) or while_FP() while_FP()
推荐答案
FP- style不使用全局状态(全局变量)并将副作用降至最低(例如,IO)。 while-loop shout看起来像这样:
FP-style don't uses global state (global variables) and minimizes the side effects (IO for ex.). While-loop shout look like this:
fp_while = lambda pred, fun, acc: (lambda val: fp_while(pred, fun, val) if pred(val) else val)(fun(acc)) print fp_while(lambda x: x < 5, lambda x: x + 1, 1)
如果您需要副作用:
if you need a side effect:
def add_and_print(x): print x return x + 1 fp_while(lambda x: x < 5, add_and_print, 1)
这篇关于函数式编程 - for和while循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!