Using itertools for recursive function application

后端 未结 2 1493
时光取名叫无心
时光取名叫无心 2021-02-15 17:22

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 a

2条回答
  •  梦毁少年i
    2021-02-15 18:10

    You can use an anamorphism (or unfold) to simplify the definition of iterate, and to use only one starting value. Here's an implementation I once used, based on a quite well-known paper:

    def ana(build, predicate):
        def h(x):
            if predicate(x):
                return
            else:
                a, b = build(x)
                yield a
                for i in h(b):
                    yield i
                # with newer syntax: 
                # yield from h(b)
        return h
    

    Implementing iterate with ana then looks like this:

    def iterate(f, x):
        return ana(lambda x: (x, f(x)), lambda _: False)(x)
    

    No itertools, though... And I agree that this isn't the most readable variant. In fact, it is rather cryptic.


    UPDATE: There's an easier version, which even looks quite nice. It's taken from here:

    def unfold(f, x):
        while True:
            w, x = f(x)
            yield w
    

    And that gives you:

    def iterate(f, x):
        return unfold(lambda y: (y, f(y)), x)
    

提交回复
热议问题