计算两个列表中匹配元素的数量 [英] Count number of matching elements in two lists
问题描述
我有 2 个包含随机元素数量的列表.例如 A=[1,2,4,5] 和 B=[1,2,3].结果应该是2.我试过的代码:
I have 2 lists with random number of elemets. Eg A=[1,2,4,5] and B=[1,2,3]. Result should be 2. Code that I tried:
domains
Numbers1 = integer*
Numbers2 = integer*
int_list=integer*
predicates
nondeterm prinadl(integer, int_list)
clauses
//here going the code that read number that I've entered, and according to entered numer,programm should do something
answer(T):- T=5,
P = 0,
write ("Enter the 1st list"), readterm (int_list, L),
write ("Enter the 2nd list"), readterm (int_list, L2),
L2 = [H|V], prinadl(H, L), P1 = P + 1,
write(L2, P1, V).
prinadl (X, L):- L=[X|_], !.
prinadl (X, L):- L=[_|T], prinadl (X, T).
我对 prolog 完全陌生.你能告诉我我错在哪里吗?我所需要的只是获取打印到控制台的匹配数.提前致谢.
I'm totally new with prolog. Can you please say me where I'm wrong? All I need is to get number of matches printed to the console. Thanks in advance.
推荐答案
这个答案基于两件事:第一,猜测.第二,@false 的 if_/3
.
This answer is based on two things: first, guesswork. second, if_/3
by @false.
让我们定义meta-predicate count_left_while2/4
.
count_left_while2(P_2,Xs,Ys,N)
计数满足P_2
的Xs
和Ys
中对应列表项的数量N
.从左到右,count_left_while2
在不满足 P_2
的前两项停止.当一个列表为空时它也会停止,但另一个不是.
count_left_while2(P_2,Xs,Ys,N)
counts
the number N
of corresponding list items in Xs
and Ys
fulfilling P_2
. Proceeding from left to right, count_left_while2
stops at the first two items not satisfying P_2
. It also stops when one list is empty, but the other one is not.
:- use_module(library(clpfd)).
:- meta_predicate count_left_while2(2,?,?,?).
count_left_while2(P_2,Xs,Ys,N) :-
N #>= 0,
list_list_countleft_while(Xs,Ys,N,P_2).
nil_or_cons([]).
nil_or_cons([_|_]).
:- meta_predicate list_list_countleft_while(?,?,?,2).
list_list_countleft_while([],Xs,0,_) :-
nil_or_cons(Xs).
list_list_countleft_while([X|Xs],Ys,N,P_2) :-
list_list_prev_countleft_while(Ys,Xs,X,N,P_2).
:- meta_predicate list_list_prev_countleft_while(?,?,?,?,2).
list_list_prev_countleft_while([],_,_,0,_).
list_list_prev_countleft_while([Y|Ys],Xs,X,N,P_2) :-
if_(call(P_2,X,Y),
( N0 #>= 0, N #= N0+1, list_list_countleft_while(Xs,Ys,N0,P_2) ),
N = 0).
让我们将它与具体的术语相等谓词(=)/3
结合使用,像这样:
Let's use it in combination with reified term equality predicate (=)/3
, like this:
:- count_left_while2(=,[1,2,4,5],[1,2,3],N).
N = 2.
这篇关于计算两个列表中匹配元素的数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!