gpt4 book ai didi

prolog - 查找相邻成员

转载 作者:行者123 更新时间:2023-12-01 09:26:05 25 4
gpt4 key购买 nike

我必须找出列表的两个成员是否相邻。限制是使用 append/3 谓词。到目前为止,我已经完成了以下操作,如果它是真的,它会起作用,否则我没有得到任何答案,就像它永远运行一样。

adjacent(X,Y,L):-
append(L1,[X,Y],T1),append(T1,T2,L).

最佳答案

要查看您的程序是否会循环,只需考虑以下 :

    adjacent(X,Y,L):-       append(L1,[X,Y],T1), false,       append(T1,T2,L).

If this program will loop, then the original program will loop too. It might succeed, but still it will loop.

In your first goal both L1 and T1 are uninstantiated variables - that's easy to see, because they are not used anywhere else in this fragment. As a consequence, this program will always loop, no matter what X, Y or L might be. To fix this, you have to modify something in the visible part.

One possibility would be to exchange the two goals. But there is an even easier way out:

adjacent(X,Y,L) :-
append(_,[X,Y|_],L)

但是请注意,这并不能确保 L 确实是一个格式正确的列表。事实上,adjacent(1,2,[1,2|nonlist]) 成功了。如果它应该是一个列表:

adjacent(X,Y,L) :-
append(_,[X,Y|R],L),
append(R,[],R).

了解更多。

关于prolog - 查找相邻成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23516616/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com