我在这里修改算法:
https://eli.thegreenplace.net/2018/unification/
我只有一组字符串和数字的等式。例如对于以下集合 l = [('x1', 'x2'), ('x2', 'x3')] 我希望映射说例如 {x1:x2, x2:x2, x3:x2 }。相反,我得到{'x1':'x2','x2':'x3'}。
这是修改后的代码。我不担心发生检查或除常量和字符串(变量)之外的任何其他结构。
def unify(x, y, subst):
"""Unifies term x and y with initial subst.
Returns a subst (map of name->term) that unifies x and y, or None if
they can't be unified. Pass subst={} if no subst are initially
known. Note that {} means valid (but empty) subst.
"""
if subst is None:
return None
elif x == y:
return subst
elif isinstance(x, str):
return unify_variable(x, y, subst)
elif isinstance(y, str):
return unify_variable(y, x, subst)
else:
return None
def unify_variable(v, x, subst):
"""Unifies variable v with term x, using subst.
Returns updated subst or None on failure.
"""
assert isinstance(v, str)
if v in subst:
return unify(subst[v], x, subst)
elif isinstance(x, str) and x in subst:
return unify(v, subst[x], subst)
else:
return {**subst, v: x}
l = [('x1', 'x2'), ('x2', 'x3')]
subst = {}
for c in l:
subst = unify(c[0], c[1], subst)
结果:{'x1': 'x2', 'x2': 'x3'}
有没有办法修改它以引用此映射范围内的相同变量?