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 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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With