开发者

Stack overflow in Prolog

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜