0

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?

gipo
  • 19
  • 4

3 Answers3

1

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.
Community
  • 1
  • 1
repeat
  • 18,496
  • 4
  • 54
  • 166
0

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].

Vennik
  • 565
  • 3
  • 11
  • Nearly perfect. Have edited original to show the result and what I would like if possible. – gipo Apr 22 '15 at 19:34
  • That is perfect for what I need, Thanks – gipo Apr 24 '15 at 14:40
  • In Prolog it is good practise to **always** put the responsibility regarding the use of `(!)/0` to the "callee", not the "caller". Your previous version was better. – repeat Apr 24 '15 at 17:30
0

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).
Ludwig
  • 101
  • 1
  • 3