功能风格的Conjoin功能

ovg*_*vin 5 python functional-programming

最近,阅读Python "功能编程HOWTO",我遇到了一个提到test_generators.py标准模块,在那里我找到了以下生成器:

# conjoin is a simple backtracking generator, named in honor of Icon's
# "conjunction" control structure.  Pass a list of no-argument functions
# that return iterable objects.  Easiest to explain by example:  assume the
# function list [x, y, z] is passed.  Then conjoin acts like:
#
# def g():
#     values = [None] * 3
#     for values[0] in x():
#         for values[1] in y():
#             for values[2] in z():
#                 yield values
#
# So some 3-lists of values *may* be generated, each time we successfully
# get into the innermost loop.  If an iterator fails (is exhausted) before
# then, it "backtracks" to get the next value from the nearest enclosing
# iterator (the one "to the left"), and starts all over again at the next
# slot (pumps a fresh iterator).  Of course this is most useful when the
# iterators have side-effects, so that which values *can* be generated at
# each slot depend on the values iterated at previous slots.

def simple_conjoin(gs):

    values = [None] * len(gs)

    def gen(i):
        if i >= len(gs):
            yield values
        else:
            for values[i] in gs[i]():
                for x in gen(i+1):
                    yield x

    for x in gen(0):
        yield x
Run Code Online (Sandbox Code Playgroud)

我花了一段时间才明白它是如何工作的.它使用一个可变列表values来存储迭代器的结果,而N + 1迭代器返回它values,它通过整个迭代器链.

当我在阅读函数式编程时偶然发现这段代码时,我开始考虑是否可以使用函数式编程(使用itertools模块中的函数)重写这个连接生成器.有很多(在刚刚结束一目了然写函数式程序的这个文章中的食谱节).

但是,遗憾的是,我还没有找到任何解决方案.

那么,是否可以使用itertools模块使用函数编程来编写这个连接生成器?

谢谢

rec*_*ive 3

这似乎有效,但仍然很懒:

def conjoin(gs):
    return [()] if not gs else (
        (val,) + suffix for val in gs[0]() for suffix in conjoin(gs[1:])
    )

def range3():
    return range(3)

print list(conjoin([range3, range3]))
Run Code Online (Sandbox Code Playgroud)

输出:

[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]
Run Code Online (Sandbox Code Playgroud)

显示可变状态的示例用法:

x = ""
def mutablerange():
    global x
    x += "x"
    return [x + str(i) for i in range(3)]

print list(conjoin([range3, mutablerange]))
Run Code Online (Sandbox Code Playgroud)

输出:(观察“x”数量的增加)

[(0, 'x0'), (0, 'x1'), (0, 'x2'), (1, 'xx0'), (1, 'xx1'), (1, 'xx2'), (2, 'xxx0'), (2, 'xxx1'), (2, 'xxx2')]
Run Code Online (Sandbox Code Playgroud)

如果我们使用itertools.product

x = ""
print list(itertools.product(range3(), mutablerange()))
Run Code Online (Sandbox Code Playgroud)

结果如下:

[(0, 'x0'), (0, 'x1'), (0, 'x2'), (1, 'x0'), (1, 'x1'), (1, 'x2'), (2, 'x0'), (2, 'x1'), (2, 'x2')]
Run Code Online (Sandbox Code Playgroud)

因此,我们可以清楚地看到,它itertools.product缓存了迭代器返回的值。

  • “价值观”的可变性不是核心问题。这些函数改变了一些其他东西(任何东西),这些东西在运行之间保持变化,因此它们的下一次运行可能会受到上一次运行的影响。这就是为什么不可能创建一个真正有用的函数实现(递归是其中之一,而不是同时两者)——函数必须有副作用(不是纯粹的)才能有用与“simple_conjoin”。没有副作用,正如其他人提到的那样,它只是笛卡尔积。 (2认同)