How to exam every 3 consecutive items of a list in prolog

Viewed 28

I have a list in prolog like this: [a,b,c,d,e].

Then the idea is to exam every 3 items like [a,b,c]; do something with a and c, then store b. The same goes for [b,c,d], and [c,d,e]... until I run out of the combination of 3.

How does the recursion work here? I tried something below but could not figure out how to safely exit and/or preserve the list M

% write(M). gave memo address
%[_,_] will be caught if there are less than 3 items in the list

con([_,_],M) :- M. 

con([a,b|[c|T]],M) :-
  a < b,
  con([b|[c|T]],[b|M]).

con([a,b|[c|T]],M) :-
  a > b,
  con([b|[c|T]],[b|M]).
1 Answers

You can make use of unification with the [A, B, C |T] pattern:

con([A, B, C | T], …) :-
    %% …,
    con([B, C | T], …).
con([_,_], …).
con([_], …).
con([], …).

where the … parts are other parameters, predicate calls, etc. We thus each time unify with [A, B, C |T] such that A is the first, B the second and C the third parameter, and we recurse by calling this with [B,C|T] such that the first element is removed in the recursive call.

Related