Coolest Python recipe of all time

Ian Kelly ian.g.kelly at gmail.com
Fri May 6 15:38:08 EDT 2011


On Fri, May 6, 2011 at 12:36 PM, Ian Kelly <ian.g.kelly at gmail.com> wrote:
> This is typically implemented using continuations, and I'm not sure
> whether a true amb could actually be achieved in Python without adding
> continuations or flow-control macros to the language.

I stand corrected.  After poking around a bit more I found this recipe
that is designed for unit-testing but implements amb beautifully.

http://lackingrhoticity.blogspot.com/2009/08/how-to-do-model-checking-of-python-code.html

My code from the previous post using this recipe:

def find_values(chooser):
    def amb(*choices):
        return chooser.choose(choices)
    def require(x):
        if not x:
            amb()
    a = amb(1, 3, 5)
    b = amb(2, 4, 8)
    require(a + b > 5)
    require(is_prime(a * b + 1))
    c = amb(a, b, None)
    require(c is None or c >= 5)
    return a, b, c

check(find_values)

The one downside is that the check function (again, designed for
unit-testing) does not provide any way to retrieve the returned
values, but that is easily solved by rewriting as a generator.

Cheers,
Ian



More information about the Python-list mailing list