I need a Python function iterate(f, x)
that creates an iterator returning the values x, f(x), f(f(x)), f(f(f(x))), etc (like, e.g., Clojure's iterate
). First of all, I was wondering: Does this already exist somewhere in the standard library and I'm only missing it? Of course it's easy enough to implement with a generator:
def iterate(f, x):
while True:
yield x
x = f(x)
Just out of curiosity: Is there a more functional way to do this in Python, e.g. with some itertools or functools magic?
In Python 3.3 this would work
def iterate(f, x):
return accumulate(repeat(x), lambda acc, _ : f(acc))
but looks like an abuse to me. Can I do this more nicely?