给定替换 S 和列表 X,如何将 S 应用于 X
假设我有一个替换 S 和列表 Xs,其中 Xs 中出现的每个变量也出现在 S 中。我如何找到列表S(Xs),即通过将替换S应用于列表Xs而获得的列表。
更具体地说,我有一组谓词和 DCG 规则,看起来像
pat(P) --> seg(_), P, seg(_).
seg(X,Y,Z) :- append(X,Z,Y).
如果我尝试将模式 P 与列表中的变量进行匹配,我会收到替换 S:
?- pat([a,X,b,Y],[d,a,c,b,e,d],[]).
X = c,
Y = e
我想将替换 S = {X = c, Y = e} 应用于具有变量 X 和 Y 的列表 Xs ,并收到已替换的列表,但我不确定解决问题的最佳方法是什么。
如果我在 Haskell 中解决这个问题,我会构建一个从变量到值的有限映射,然后执行替换。等效的方法是在 DCG 规则中生成变量和值对的列表,然后使用该映射来查找所需的列表。然而,这不是一个合适的方法。
Suppose I have a substitution S and list Xs, where each variable occurring in Xs also occurs in S. How would I find the list S(Xs), i.e., the list obtained by applying the substitution S to the list Xs.
More concretely, I have a set of predicates and DCG rules that look something like
pat(P) --> seg(_), P, seg(_).
seg(X,Y,Z) :- append(X,Z,Y).
If I attempt to match a pattern P with variables against a list, I receive a substitution S:
?- pat([a,X,b,Y],[d,a,c,b,e,d],[]).
X = c,
Y = e
I want to apply the substitution S = {X = c, Y = e} to a list Xs with variables X and Y, and receive the list with substitutions made, but I'm not sure what the best way to approach the problem is.
If I were approaching this problem in Haskell, I would build a finite map from variables to values, then perform the substitution. The equivalent approach would be to produce a list in the DCG rule of pairs of variables and values, then use the map to find the desired list. This is not a suitable approach, however.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
由于替换没有具体化(不是 Prolog 对象),因此您可以将列表绑定到变量并让统一完成其工作:
编辑:如果您想在替换后保留原始列表,使用
copy_term
:Since the substitution is not reified (is not a Prolog object), you can bind the list to a variable and let unification do its work:
Edit: If you want to keep the original list around after the substitution, use
copy_term
: