Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: is it possible to mix generator and a recursive function?

Is there a way to make the something like the following code work?

add = lambda n: (yield n) or add(n+1)

(answers don't need to be in functional style)

like image 782
Lord British Avatar asked Jul 18 '10 19:07

Lord British


1 Answers

def add(n):
    yield n
    for m in add(n+1):
        yield m

With recursive generators it's easy to build elaborate backtrackers:

def resolve(db, goals, cut_parent=0):
    try:
        head, tail = goals[0], goals[1:]
    except IndexError:
        yield {}
        return
    try:
        predicate = (
            deepcopy(clause)
                for clause in db[head.name]
                    if len(clause) == len(head)
        )
    except KeyError:
        return
    trail = []
    for clause in predicate:
        try:
            unify(head, clause, trail)
            for each in resolve(db, clause.body, cut_parent + 1):
                for each in resolve(db, tail, cut_parent):
                    yield head.subst
        except UnificationFailed:
            continue
        except Cut, cut:
            if cut.parent == cut_parent:
                raise
            break
        finally:
            restore(trail)
    else:
        if is_cut(head):
            raise Cut(cut_parent)

...

for substitutions in resolve(db, query):
    print substitutions

This is a Prolog engine implemented by a recursive generator. db is a dict representing a Prolog database of facts and rules. unify() is the unification function that creates all substitutions for the current goal and appends the changes to the trail, so they can be undone later. restore() does the undoing, and is_cut() tests if the current goal is a '!', so that we can do branch pruning.

like image 140
pillmuncher Avatar answered Sep 21 '22 01:09

pillmuncher