如何使用julia的协程


#1
from typing import List


def all_order(n: int, c: List[int]):
    if len(c) == n:
        yield c
    elif len(c) < n:
        for i in range(n):
            v = i + 1
            if v in c:
                continue
            c.append(v)
            for result in all_order(n, c):
                yield result
            c.pop()


for r in all_order(3, []):
    print(r)

输出如下

[1, 2, 3]
[1, 3, 2]
[2, 1, 3]
[2, 3, 1]
[3, 1, 2]
[3, 2, 1]

请教如何在julia中使用协程实现相同的功能?


#2

Channel 只接受单参函数,所以有点啰嗦。
感觉应该有更优雅的写法,权当抛砖引玉吧。

function all_order(n::Int, l::Vector=[])
    Channel(c->producer(c, n, l))
end

function producer(c::Channel, n, l)
    if length(l) == n
        put!(c, l)
    elseif length(l) < n
        for i in 1:n
            if i in l
                continue
            end
            for r in all_order(n, vcat(l, i))
                put!(c, r)
            end
        end
    end
end

for r in all_order(3)
    println(r)
end
Any[1, 2, 3]
Any[1, 3, 2]
Any[2, 1, 3]
Any[2, 3, 1]
Any[3, 1, 2]
Any[3, 2, 1]

参考文档