user2211776
user2211776

Reputation: 267

List intersection predicate issue

I'm trying to create this predicate that counts the number of matches from one list to another but whenever I run it I keep getting errors regarding the X and Y values not being instantiated correctly. Does anybody know how to fix this?

:- dynamic listCount/1.
listCount(0).

intersection([],_,_).
intersection([H|T], CheckingList, _):-
    member(H,CheckingList),                      %checks if it's within the list
    deleteFromList(CheckingList, H, NewList),    %deletes all occurrences form the list
    listCount(X),                                %retrieves the persistent value
    retractall(listcount(_)),
    Y is X + 1,                                  &increments the value
    assert(listcount(Y)),
    intersection(T, NewList,Y).                  %recurses  on the remaining list

Upvotes: 1

Views: 171

Answers (2)

Will Ness
Will Ness

Reputation: 71065

The SWI Prolog has intersection predicate as part of its library.

If you must write this yourself,

my_intersection(A,B,C):-
  findall( X, (member(X,A), memberchk(X,B)), C).

you should not use here any assert/retract calls.

Then, trivially,

intersection_count(A,B,N):-
  my_intersection(A,B,C),
  length(C,N).

Upvotes: 0

CapelliC
CapelliC

Reputation: 60004

There are several typos (like listcount vs listCount), but overall there is a big misconception: assert/retract are not necessary to implement this functionality, and should be avoided. Counting matches can be done (for instance) with library(aggregate):

counts_matches(L1,L2,N) :-
  aggregate_all(count, (member(X,L1),memberchk(X,L2)), N).

Upvotes: 1

Related Questions