1
votes

i have a task to create a list of sublists where the elements are sorted in consecutive order. I'm having difficulties because when it iterates through the list and returns multiple lists with a list, thats not what i want. My goal is a list with multiple sublists of length 3.

example

list([]).
list([_|T]) :- list(T).

sublist(L, []) :- list(L).
sublist([HX|TX],[HX|TY]) :- sublist(TX,TY).
sublist([_|TY], X) :- X = [_|_], sublist(TY, X).

This prints out every single sublist.

?- sublist([10,20,30,a,b], L).
L = [] ;
L = [10] ;
L = [10, 20] ;
L = [10, 20, 30] ;
L = [10, 20, 30, a] ;
L = [10, 20, 30, a, b] ;
L = [10, 20, 30, b] ;
..and so on

What i want is something like this

?- sublist([10,20,30,a,b], L).
L = [[10,20,30],[20,30,a],[30,a,b]] 

I've been overthinking this i guess, and other thing X = [_,_,_] destroys my functionality.

1

1 Answers

2
votes

You can use append/3 to obtain all the "sliding" sublists.

For the specific case of 3 elements:

sublist(L, LSubL):-
  findall([A,B,C], append(_, [A,B,C|_], L), LSubL).

For the more general case of sliding window of 'Size' items:

sliding_window(L, Size, LSubL):-
  length(SubL, Size),
  append(SubL, _, SubLO),
  findall(SubL, append(_, SubLO, L), LSubL).