我正在努力编写更具可读性、声明性的程序。所以我决定实现一个我们目前使用的简单算法。程序实现如下:
因此,我提出的数据日志变体看起来不错,但有两个问题:
您可以找到完整的源文件here。在
它取决于假设,您可以使用pytest轻松运行它。在
下面的测试失败:如果我们需要由以前的“等级”或顺序提供的资源。它找不到它。我试图使follows递归,但是即使在简单的例子中也失败了。在
def test_graph_multirequire():
"""Test if the resolver can handle a graph with multiple requires"""
tree = [
[('A'), ('B'), ('C'), ('D'), ('E'), ('F'), ('G'), ()],
[(), ('A'), ('B'), ('C', 'A'), ('D'), ('E'), ('F'), ('G')]
]
run_graph(tree)
def run_graph(tree):
"""Run an example"""
try:
tree_len = len(tree[0])
index = list(range(tree_len))
random.shuffle(index)
for i in index:
+ is_command(i)
for provide in tree[0][i]:
+ provides(i, provide)
for require in tree[1][i]:
+ requires(i, require)
##############################
is_root(X) <= is_command(X) & ~requires(X, Y)
follows(X, Z) <= (
provides(X, Y) & requires(Z, Y) & (X != Z)
)
order(0, X) <= is_root(X)
order(N, X) <= (N > 0) & order(N - 1, Y) & follows(Y, X)
##############################
ordered = []
try:
for x in range(tree_len):
nodes = order(x, N)
if not nodes:
break
ordered.extend([x[0] for x in nodes])
except AttributeError:
ordered = index
assert len(ordered) >= tree_len
print(ordered)
provided = set()
for command in ordered:
assert set(tree[1][command]).issubset(provided)
provided.update(tree[0][command])
finally:
pd.clear()
我的问题:
编辑:
pyDatalog(和prolog)很好地适应了这种问题。挑战是要脱离传统的程序化编程思维。您可能想在网上搜索prolog课程:许多原则也适用于pyDatalog。在
用声明性语言编写循环包括3个步骤:
1)定义一个谓词,其中包含在循环过程中更改的所有变量。在
在这种情况下,您需要跟踪部分计划、已经生成的内容和剩余的计划:
例如,partial_plan([0,],['A',],[1,2,3,4,5,6,7])为true。要查找计划,您需要查询:
^{pr2}$2)描述基本(=最简单)情况。在这里,起点是所有的命令仍然需要计划。在
3)描述迭代规则。在这里,您需要选择一个要执行的命令,以及其需求已经生成,并将其添加到Planned:
现在我们必须定义第3步中介绍的谓词。在
subset检查L1的所有元素是否在L2中(注意all量词)。它也被定义为一个循环:
然后必须声明上面所有的pyDatalog变量和谓词,以及“enumerate”、“result”和“requirement”函数。在
注意:这还没有经过测试;可能需要一些小的更改。在
相关问题 更多 >
编程相关推荐