gipo
gipo

Reputation: 19

Return a list from items matching in two lists Prolog

I am very new to Prolog and I have this :

compare_list(Hours1, Hours2, Matching) 

I want to return the matching hours between lists Hours1 and Hours2 into the list Matching

I can get the matches but not construct the list of matches.

Hours1 may be like: [1,2,3], Hours2 may be like: [2,3], So from this: Matching Hours should be: [2,3]

Help would be appreciated.

I have implemented what Vennik has suggested and it is very near to what I want. Results From Hours1 : [2,3,5], Hours2 : [2,5] Give the following:

Matching = [2, 5] ;
Matching = [2] ;
Matching = [5] ;
Matching = [] 

Is it possible to only have the first set without producing the other three results?

Upvotes: 0

Views: 327

Answers (3)

repeat
repeat

Reputation: 18726

You might want to consider the related question intersection and union of 2 lists.

In particular, my logically pure answer to above question might be of good use to you, as it offers multiple advantages over the code posted by @vennik above:

  1. The predicates behave the way relations should. "Multi-directional."
  2. They are monotone and remain sound upon arbitrary generalization / specialization.
  3. They aim at completeness of the relation of interest, creating choice points when required.
  4. They are efficient, avoiding the creation of useless choice points.

Upvotes: 1

Ludwig
Ludwig

Reputation: 101

I know that is not pure... (or not montone, if you like) ... but, if you aren't a purist, SWI-Prolog give you the predicate

intersection/3

that you can use in this way

intersection(Hours1, Hours2, Matching).

Upvotes: 0

Vennik
Vennik

Reputation: 565

Try this:

compare_list([], _, []).
compare_list([Hour | Hours1], Hours2, [Hour | Matching]) :-
    member(Hour, Hours2),
    compare_list(Hours1, Hours2, Matching).
compare_list([_ | Hours1], Hours2, Matching) :-
    compare_list(Hours1, Hours2, Matching).

Calling compare_list([1,2,3], [1,2], X), !. will result in X = [1,2].

Upvotes: 0

Related Questions