我有类似的事实:
like(sara,'data base',3).
like(sara,'math',3).
like(sara,'physics',3).
like(sara,'law',3).
like(sara,'history',5).
like(sara,'science',1).
like(tom,'chemistry',3).
like(tom,'data base',2).
like(tom,'logic',3).
like(tom,'law',3).
like(tom,'history',3).
like(tom,'science',3).
:- dynamic same_like/3.
我希望比较事实,找到一个sara和tom喜欢但具有不同等级的主题,所以我所做的是:
comp1 :-
like(sara, NofC1, X),
like(tom, NofC2, Y),
NofC1 = NofC2,
asserta( same_like(sara, NofC1, X) ),
asserta( same_like(tom, NofC2, Y) ),
same_like(sara, NC1, A),
same_like(tom, NC2, B),
NC1 = NC2,
A =\= B,
write('sara and tom like the same subject " '),
write(NC1),
write(' " .But with different level, sara= '),
write(A),
write(' And tom = '),
write(B),
nl,
fail.
答案是对的,但答案中有一个重复:
sara and tom like the same subject " data base " .But with different level, sara= 3 And tom = 2
sara and tom like the same subject " data base " .But with different level, sara= 3 And tom = 2
sara and tom like the same subject " history " .But with different level, sara= 5 And tom = 3
sara and tom like the same subject " data base " .But with different level, sara= 3 And tom = 2
sara and tom like the same subject " science " .But with different level, sara= 1 And tom = 3
sara and tom like the same subject " history " .But with different level, sara= 5 And tom = 3
sara and tom like the same subject " data base " .But with different level, sara= 3 And tom = 2
false
问题是如何删除这种重复? :(
答案 0 :(得分:2)
您不应该在不需要的情况下使用asserta / 1。您的查询可能更简单
% define a reusable query
comp1(Argument, Person1, Level1, Person2, Level2) :-
like(Person1, Argument, Level1),
like(Person2, Argument, Level2),
Person1 \= Person2, Level1 > Level2.
修改我将Level1 \= Level2
更改为Level1 > Level2
以避免重复
% use the query and display facilities
comp1 :-
forall(comp1(Argument, Person1, Level1, Person2, Level2),
format('sara and tom like the same subject " ~s " .But with different level, ~s=~d And ~s=~d~n', [Argument, Person1, Level1, Person2, Level2])).
答案 1 :(得分:0)
您可以在找到匹配后尝试添加剪辑。例如在nl。
之后 ....
nl,
!,
fail.
这可以防止超越这一点的回溯。如果这不适合你,你可以尝试一下切割的位置。