给定替换 S 和列表 X,如何将 S 应用于 X

发布于 2024-11-14 02:59:47 字数 639 浏览 3 评论 0原文

假设我有一个替换 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} 应用于具有变量 XY 的列表 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

罗罗贝儿 2024-11-21 02:59:47

由于替换没有具体化(不是 Prolog 对象),因此您可以将列表绑定到变量并让统一完成其工作:

?- Xs = [a,X,b,Y], pat(Xs,[d,a,c,b,e,d],[]).
Xs = [a, c, b, e],
X = c,
Y = e .

编辑:如果您想在替换后保留原始列表,使用copy_term

?- Xs = [a,X,b,Y], copy_term(Xs,Ys), pat(Xs,[d,a,c,b,e,d],[]).
Xs = [a, c, b, e],
X = c,
Y = e,
Ys = [a, _G118, b, _G124] .

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:

?- Xs = [a,X,b,Y], pat(Xs,[d,a,c,b,e,d],[]).
Xs = [a, c, b, e],
X = c,
Y = e .

Edit: If you want to keep the original list around after the substitution, use copy_term:

?- Xs = [a,X,b,Y], copy_term(Xs,Ys), pat(Xs,[d,a,c,b,e,d],[]).
Xs = [a, c, b, e],
X = c,
Y = e,
Ys = [a, _G118, b, _G124] .
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文