Reputation: 71
I want to write a predicate that finds a particular element in a list, by comparing the lists. For example the data I could have for instance could be like:
likes(phil, [apple, banana, orange]).
likes(hetti, [apple, cherry, grapes]).
etc.
I just want someone to explain how something like this would work, because I've been trying to use member or select; but it seems to be more difficult to find information on this. Could I use pattern matching?
Upvotes: 0
Views: 60
Reputation: 117175
It seems likely that you want to know what the common likes are between phil
and hetti
. If so, then this is the code:
?- bothlike(phil, hetti, Ls), write(Ls), nl.
bothlike(X, Y, Ls) :-
likes(X, Xs),
likes(Y, Ys),
intersection(Xs, Ys, Ls).
likes(phil, [apple, banana, orange]).
likes(hetti, [apple, cherry, grapes]).
intersection([], _, []).
intersection([H1|T1], L2, L3) :-
member(H1, L2),
!,
L3 = [H1|T3],
intersection(T1, L2, T3).
intersection([_|T1], L2, L3) :-
intersection(T1, L2, L3).
It gives the answer [apple]
.
Upvotes: 0