2010-07-18 51 views

回答

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

递归发电机可以很容易地建立复杂的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 

这是一个由递归生成器实现的Prolog引擎。 db是代表事实和规则的Prolog数据库的字典。 unify()是统一函数,为当前目标创建所有替换并将更改追加到追踪中,以便稍后可以撤消它们。 restore()执行撤消操作,is_cut()测试当前目标是否为'!',以便我们可以执行分支修剪。

+0

给出的添加示例没有终止条件。你打算这么做吗? – Alice 2015-02-01 19:45:17

3

我不知道的意图的“产量(n)或增加(N + 1)”,但递归发电机当然可能。您可能想阅读下面的链接以了解可能的情况,特别是标题为“递归生成器”的部分。

0

你的功能似乎我只想成为绑定序列等表达:

N,N + 1,N + 2,...

def add(x): 
    while True: 
     yield x 
     x+=1 

for index in add(5): 
    if not index<100: break ## do equivalent of range(5,100) 
    print(index) 

这不是递归的,但我看到这里不需要递归样式。

基于其他的答案的链接,其中有发电机调用发电机,但不是递归上的递归版本:

from __future__ import generators 

def range_from(n): 
    yield n 
    for i in range_from(n+1): 
     yield i 

for i in range_from(5): 
    if not i<100: break ## until 100 (not including) 
    print i