I am trying to write Prolog code to determine whether the bound variable X
is in the scope of the bound variable Y
in a list. Lists may be nested and X
is in the scope of Y
if X
and Y
are members of the same list or if X
is a member of a list that is a member of a list that is a member of a list...(nested indefinitely) that is in the same list as Y
. Here I define in_scope(X,Y,List)
to mean that X
is in the scope of Y
in the outermost list List
. I have written the following code, but this code results in a stack overflow:
in_scope(X,Y,List) :- in(Parent,List), member(X,Parent), member(Y,Parent).
in_scope(X,Y,List) :- in(X,Parent), in_scope(Parent,Y,List).
in(X,Y) :- member(X,Y).
in(X,Y) :- member(X,Z), in(Z,Y).
I would appreciate help in modifying the code to avoid th开发者_如何学运维e stack overflow.
I was too lazy to trace the actual error, but the following, simplified code
in_scope(X,Y,List) :- member(Y,List), in(X,List).
in_scope(X,Y,List) :- member(Sub,List), in_scope(X,Y,Sub).
in(X,List) :- member(X,List).
in(X,List) :- member(Sub,List), in(X,Sub).
gives the intended results:
?- in_scope(x,z,[x,y,z]).
true .
?- in_scope(x,z,[[x,y],z]).
true .
?- in_scope(x,z,[[[[[x],y]],z]]).
true .
?- in_scope(x,a,[[[[[x],y]],z]]).
false.
But note the following; I'm not sure if this is intended behavior:
?- in_scope(x,x,[x]).
true .
精彩评论