Prolog 中的堆栈溢出

发布于 2024-09-28 17:42:48 字数 625 浏览 6 评论 0原文

我正在尝试编写 Prolog 代码来确定绑定变量 X 是否在列表中绑定变量 Y 的范围内。列表可以嵌套,并且如果 XY 是同一列表的成员,则 X 位于 Y 的范围内或者如果X是一个列表的成员,该列表是一个列表的成员,该列表是一个列表的成员...(无限嵌套)与Y.这里我定义in_scope(X,Y,List)表示X在最外层列表List中Y的范围内。我编写了以下代码,但此代码会导致堆栈溢出:

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 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 the stack overflow.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

叹梦 2024-10-05 17:42:48

我懒得追踪实际的错误,但下面的简化代码

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

给出了预期的结果:

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

但请注意以下几点;我不确定这是否是预期行为:

?- in_scope(x,x,[x]).
true .

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 .
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文