Search code examples
pythonfunctional-programming

Functional programming — for and while loops


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()

Solution

  • 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)