2012-12-08 45 views
1

我有這樣的事實:在序言比較兩個事實

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. 

,我要比較的事實中找到的一個主題,無論薩拉和湯姆一樣,但不同的水平,所以我做的是:

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

您可以在NL後,嘗試加入一個切找到匹配後。例如,

.... 
    nl, 
    !, 
    fail. 

以及防止回溯超出了這一點。如果不適合你,你可以實驗一下與切口的位置。

+0

我這樣做,但如果我用!不是所有的答案都會被打印出來:( – user1885169

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 \= Level2Level1 > 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])). 
+0

這是工作正常,非常感謝^ _ ^ – user1885169