Coolest Python recipe of all time

Ian Kelly ian.g.kelly at gmail.com
Fri May 6 14:36:09 EDT 2011


On Fri, May 6, 2011 at 10:59 AM, Steven D'Aprano
<steve+comp.lang.python at pearwood.info> wrote:
> As written, amb is just a brute-force solver using more magic than is
> good for any code, but it's fun to play with.

This isn't really amb; as you said it's just a brute-force solver with
some weird syntax.  The whole point of amb is to enable
non-deterministic programming, such as this:

def find_values():
    a = amb(1, 3, 5)
    b = amb(2, 4, 8)
    if a + b <= 5:
        fail()
    if not is_prime(a * b + 1):
        fail()
    c = amb(a, b, None)
    if c is not None and c < 5:
        fail()
    return a, b, c

The amb engine would conceptually execute this function for every
possible combination of a, b, and c, pruning away the combinations
that fail at some point, and arbitrarily returning one of the
remaining combinations.  So find_values() here might return (3, 4,
None) after failing at one point or another on (1, 2); (1, 4); (1, 8);
(3, 2); (3, 4, 3); and (3; 4; 4).

Note in particular that the declaration of c is not easily expressible
using the Python recipe.

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.



More information about the Python-list mailing list