Search code examples
listprologsublist

Prolog - Find sublists in order


I am currently using this in my Prolog program:

sublist(X, L) :- append(_, S, L), append(X, _, S).

It will correctly list the sublists of a list if I call it like so,

?- sublist(A, [1, 2, 3]).
A = [] ;
A = [1] ;
A = [1, 2] ; 
A = [1, 2, 3] ;
A = [] ;
A = [2] ;
A = [2, 3] ;
A = [] ;
A = [3] ;
A = [] ;
false.

I am looking to make a new function that will try all the shorter substrings first, so that it will come up with something more like

[1] ; [2] ; [3] ; [1, 2] ; [2, 3] ; [1, 2, 3].

Taking out the empty lists isn't vital, but would be preferred.


Solution

  • I swapped arguments order, for readability - please forgive me :)

    sublist(L, S) :-
     length(L, N),
     between(1, N, M),
     length(S, M),
     append([_,S,_], L).
    

    yields

    ?- sublist([a,b,c],S).
    S = [a] ;
    S = [b] ;
    S = [c] ;
    S = [a, b] ;
    S = [b, c] ;
    S = [a, b, c] ;
    false.