Given a substitution S and list Xs, how to apply S to Xs

十年热恋 提交于 2019-12-10 21:03:39

问题


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.


回答1:


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] .


来源:https://stackoverflow.com/questions/6247621/given-a-substitution-s-and-list-xs-how-to-apply-s-to-xs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!