How to count the number of loops with functional programming style

This is a way of counting a number of loops like normal:

current_money = 10
count = 0
while current_money != 0:
    do_something(current_money)
    count += 1
print(count)

I’m still on the way to learn functional programming style so it’s quite confused when organizing my thoughts. How can I make this to become functional programming style? Thanks.

Your example cannot work for immutable content (int) of current_money. Unless do_something() modifies current_money as a global variable which a) is a bad style, b) does not make much sense with additionally passing current_money as an argument.

I think you rather mean the following operation inside the loop?

current_money = do_something(current_money)

Anyway pure functional programming does not know loops. They must be implemented using recursion. I think in Python deep recursion can bring a huge performance penalty. Practical approach is to combine multiple styles.

Your code is fine in Python. As an alternative you can change the while loop (takes care of the end condition) into for loop (takes care of the counter iteration). I changed the condition to a more robust one you probably really meant (current_money > 0).

import itertools

def do_something(money):
    return money - 2

current_money = 10
for count in itertools.count(start=1):
    current_money = do_something(current_money)
    if current_money <= 0:
        break
print(count)

…and this is functional style (with recursion):

def do_something(money):
    return money - 2

def looper(data, operation, end_condition, count):
    return (
            (data, count) if end_condition(data)
            else looper(operation(data), operation, end_condition, count + 1))

print(looper(10, do_something, lambda x: x <= 0, 0)[1])

I think the functional style is harder to understand. I use it only in small parts of my code.

1 Like