简体   繁体   中英

Equivalent of Haskell “until” in Python

Is there any built-in equivalent to Haskell's until function in Python?

Essentially, until applies a function f to a provided starting value v , then applies f to f(v) , until a condition is met. In other words, until returns the result of repeatedly applying f until a condition holds.

I can implement this in Python like so:

def until(cond, func, starting):
    val = starting
    while not cond(val):
        val = func(val)
    return val

Should I use this implementation, or is there some library function I should be using instead?

No, there is no built-in function equivalent to until . Python's built-in and itertools module has taken many things from Haskell, but not the until function. Yours is also probably the simplest and most efficient way to implement it.

In fact the real problem is that there is no function that returns the results of applying a function f iterated, so you somehow have to write the iter_apply function to do that.

When you implement iter_apply it's quite easy to compose some built-in functions to obtain until :

#from itertools import ifilter as filter  # in python2

def iter_apply(func, value):
    while True:
        yield value
        value = func(value)

def until2(cond, func, starting):
    return next(filter(cond, iter_apply(func, starting)))

# or:

from itertools import dropwhile
def until3(cond, func, starting):
    iterated_values = iter_apply(func, starting)
    return next(dropwhile(lambda x: not cond(x), iterated_values))

Time differences:

In [12]: %timeit until(lambda x: x > 10000, lambda x: x+1, 0)
100 loops, best of 3: 2.33 ms per loop

In [13]: %timeit until2(lambda x: x > 10000, lambda x: x+1, 0)
100 loops, best of 3: 2.45 ms per loop

In [14]: %timeit until3(lambda x: x > 10000, lambda x: x+1, 0)
100 loops, best of 3: 3.81 ms per loop

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM