使用list_counts/2
定义mostcommonitem_in/2
如下保留logical-purity:
mostcommonitem_in(E,Xs) :-
list_counts(Xs,Cs), % tag items with multiplicity
maplist(\ (X-N)^(M-X)^(M is -N),Cs,Ps), % prepare keysorting
keysort(Ps,[Max-_|_]), % sort ascending by negated count
member(Max-E,Ps). % pick most common ones
让我们运行一个查询!
?- mostcommonitem_in(X,[a,b,c,d,a,b,c,a,b]).
X = a ;
X = b ;
false. % OK
但是,它还是单调的吗?
?- mostcommonitem_in(X,[A,B,C,D,A,B,C,A,B]), A=a,B=b,C=c,D=d.
X = A, A = a, B = b, C = c, D = d ;
X = B, B = b, A = a, C = c, D = d ;
false. % OK: monotone
速度有多快? (相对于纯答案我在my previous answer to this question显示)
% OLD
?- length(Xs,5), time(findall(t,mostcommon_in(E,Xs),Ts)), length(Ts,N_sols).
% 854,636 inferences, 0.115 CPU in 0.115 seconds (100% CPU, 7447635 Lips)
N_sols = 71, Xs = [_,_,_,_,_], Ts = [t,t,t|...].
?- length(Xs,6), time(findall(t,mostcommon_in(E,Xs),Ts)), length(Ts,N_sols).
% 4,407,975 inferences, 0.449 CPU in 0.449 seconds (100% CPU, 9813808 Lips)
N_sols = 293, Xs = [_,_,_,_,_,_], Ts = [t,t,t|...].
?- length(Xs,7), time(findall(t,mostcommon_in(E,Xs),Ts)), length(Ts,N_sols).
% 24,240,240 inferences, 2.385 CPU in 2.384 seconds (100% CPU, 10162591 Lips)
N_sols = 1268, Xs = [_,_,_,_,_,_,_], Ts = [t,t,t|...].
% NEW
?- length(Xs,5), time(findall(t,mostcommonitem_in(E,Xs),Ts)), length(Ts,N_sols).
% 4,031 inferences, 0.001 CPU in 0.002 seconds (93% CPU, 2785423 Lips)
N_sols = 71, Xs = [_,_,_,_,_], Ts = [t,t,t|...].
?- length(Xs,6), time(findall(t,mostcommonitem_in(E,Xs),Ts)), length(Ts,N_sols).
% 17,632 inferences, 0.002 CPU in 0.002 seconds (100% CPU, 9194323 Lips)
N_sols = 293, Xs = [_,_,_,_,_,_], Ts = [t,t,t|...].
?- length(Xs,7), time(findall(t,mostcommonitem_in(E,Xs),Ts)), length(Ts,N_sols).
% 82,263 inferences, 0.023 CPU in 0.023 seconds (100% CPU, 3540609 Lips)
N_sols = 1268, Xs = [_,_,_,_,_,_,_], Ts = [t,t,t|...].
most_common([A,A,B,F,F,d,F,S,d,S,d,S,d,S],E )。 E = f。 – Tom 2010-12-04 19:20:35
这是完整代码的部分:most_common([X | Y],C): - count_runs([X | Y],K),last(K,C)。 %,所以我们有排序列表K和使用Last()我们发现字母 last([N-Y],Y)。 last([_ | Tail],Y): - last(Tail,Y)。让我们说我们有这样一个列表: \t most_common([a,a,b,f,f,d,f,s,d,s,d,s,d,s],E)。 - > last([1-b,1-f,1-s,1-f,1-s,1-f,1-s,... - ... |],a)和最常见的项目是一个但不是F,所以我们有一个小问题:D – Tom 2010-12-04 19:28:27