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.

4

3 回答 3

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.

于 2012-11-27T18:03:12.280 回答
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.

于 2012-11-27T17:58:09.757 回答
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)
于 2012-11-27T17:58:39.430 回答