Prolog 序言,寻找最佳匹配
我有几个序言事实:Prolog 序言,寻找最佳匹配,prolog,pattern-matching,intersection,Prolog,Pattern Matching,Intersection,我有几个序言事实: 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)] 从这个
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,但我不知道如何递归所有关系/2
谓词并测试每个谓词,在只返回最佳匹配之前。最佳解决方案是无法改进的:
\+更好的候选人(目标、解决方案)
。当然,您可以实现更精细的比较技术,而不是简单的长度比较
:- 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.