mgt
mgt

Reputation: 87

how to compare elements of a lists in prolog

how do you compare two lists to see if then are different

?- compare_lists(X,Y).  

Upvotes: 0

Views: 167

Answers (2)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476557

You can make use of maplist/3 [swi-doc] here with (\=) [swi-doc] as the goal:

compare_list(LA, LB) :-
    maplist((\=), LA, LB).

Upvotes: 1

max66
max66

Reputation: 66200

What about as follows ?

compare_list([], []).

compare_list([H1 | T1], [H2 | T2]) :-
  H1 \= H2,
  compare_list(T1, T2).

This require that both lists have the same length to return true; if you want true also from list of different length, you have to double the ground case of the recursion, so instead

compare_list([], []).

you can write

compare_list([], _).

compare_list(_, []).

Upvotes: 2

Related Questions