0

I have this recursive function:

def lifecycle(population):
    ...
    lifecycle(new_population)

I want to perform this loop 100 times. I want to use correct functional style. So, I cannot use a counter? Because assigning new values to a variable is not okay in functional programming. How does one do this functionally? I'm using Python.

protonpopsicle
  • 481
  • 1
  • 4
  • 12

3 Answers3

4

Technically, like this:

def lifecycle(population, i):
    if i == 100:
        return ...
    ...
    return lifecycle(new_population, i + 1)

But this is a really, really silly thing to do in Python (and it fails for all but the smallest examples, due to tail calls being not optimized). Just use a loop, although that uses mutable state under the hood, the remaining program can be perfectly functional.

2

You do it recursively, and by adding a decreasing (or increasing) loop variable.

def lifecycle(population, n):
    if n == 0:
        return population
    ...
    return lifecycle(new_population, n-1)

You must return the population if you want it to be truly functional because functional programming frowns upon side-effects.

Emil Vikström
  • 90,431
  • 16
  • 141
  • 175
1

Something like this for example:

def lifecycle(population, n, maxN):
    if n >= maxN: return
    new_population = population
    lifecycle(new_population, n+1, maxN)

lifecycle(['an initial population or something'], 0, 1000)
piokuc
  • 25,594
  • 11
  • 72
  • 102