2012-04-19 121 views
4

我有幾個Prolog的事實:序言,找到最佳匹配

relation('Kitchen', [item(spoon), item(fork), item(knife) ]). 
relation('Lounge', [item(sofa), item(chair), item(table) ]). 
relation('Bedroom', [item(bed), item(desk), item(drawers)]). 

,這是在運行時生成一個列表,例如:

[item(spoon), item(knife)] 

從這個列表中,在這種情況下,我想要'廚房'歸還,因爲它是最好的匹配。

我想我需要使用intersection/3謂詞來獲得運行列表中有多少匹配的計數,所以Kitchen會返回2,其他的會返回0,但我不知道遞歸方式通過所有的relation/2謂詞並測試每一個,然後才返回最佳匹配。

回答

1

最好的解決方案是無法改進的方案: \+ better_candidate(Goal,CurSolution)。當然,您可以實現更精細的比較技術,而不是簡單的長度比較。

:- use_module(library(lists)). 

relation('Kitchen', [item(spoon), item(fork), item(knife) ]). 
relation('Lounge', [item(sofa), item(chair), item(table) ]). 
relation('Bedroom', [item(bed), item(desk), item(drawers)]). 

best(X,Best) :- 
    relation(Best,BestList), intersection(X,BestList,I), 
    length(I,L), 
    \+ better_candidate(X,L). 

better_candidate(X,L) :- 
    relation(C,CList), intersection(X,CList,CI), 
    length(CI,CIL), CIL > L.