gpt4 book ai didi

prolog - 更好地理解序言

转载 作者:行者123 更新时间:2023-12-04 14:39:24 24 4
gpt4 key购买 nike

我试图了解 Prolog 以及它如何使用解析算法。我有这个例子,我发现:

hates(1, 2).
hates(2, 3).
hates(3, 4).
jealous(A, B) :- jealous(A, C), jealous(C,B).
jealous(A,B) :- hates(A,B).
但是当我试图说 jealous(1,4)然后它一直溢出并且永远不会产生真,这很奇怪,好像1讨厌2,2讨厌3,3讨厌4,那么1也应该讨厌4。
但是我尝试改变它,所以它是这样的:
hates(1, 2).
hates(2, 3).
hates(3, 4).
jealous(A,B) :- hates(A,B).
jealous(A, B) :- jealous(A, C), jealous(C,B).
然后当我说 jealous(1,4) 时它起作用了.

最佳答案

And then it works when I say jealous(1,4)


不,它没有。或者,嗯,有点。只需键入 SPACE 即可看到它再次循环。那么 jealous(4,1)哪个立即循环?
要理解这一点,只需查看程序的一小部分就足够了,即:
jealous(A,B) :- false, hates(A,B).jealous(A, B) :- jealous(A, C), false, jealous(C,B).

Note the variable B which is never used in the visible part. So it cannot have any influence on termination. And note A which is just handed to the first goal. So both arguments have no influence in this program. Thus this program terminates never. It might find a solution here and there, but it will never terminate when asked to find all of them.

This tiny fragment is called a and if it does not terminate so does your entire program! That is, there is no need to read your definition of hates/2 at all1.

If you want to master Prolog's execution, you need to master that notion of a failure slice. For, experienced programmers do this more or less by intuition. Thus, they do not read the entire program, they just scan for relevant parts. The nice thing here in Prolog being that there is a truly causal relationship between such a slice and the entire program.

To solve this problem, you need to change something in the part that has been highlighted by the failure slice. Here is one such possible change:

jealous(A,B) :- hates(A,B).
jealous(A, B) :- hates(A, C), jealous(C,B).
但是一旦您在 hates/2 中有周期,这不再有效。然后,考虑 closure/3 :
jealous(A, B) :-
closure(hates, A, B).
另一种方法是使用表格。但请注意,制表解决了这一问题,但在约束环境中将不再起作用(您迟早会遇到这种情况)。

1) 前提是你有一个纯单调的程序。

关于prolog - 更好地理解序言,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66996131/

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