Search code examples
prologdcg

Prolog challenge


I have the below implementation for the sublist algorithm. Problem: Given 2 lists, determine whether one is a sublist of the other. I would really need another distinct solution in Prolog.

Solution one:

sublist([H1|T1], L, [H2|T2]):-
  H1 = H2,
  sublist(T1, L, T2).
sublist([], _, _)
sublist([H1|T1],L,[H2|T2]):-
  sublist(L,L,T2).

Solution two:

sublist([H|T], [H|L]):- check(T,L),
sublist(S, [H|T]):- sublist(S,T).
check([H|T], [H|R]):-
   check(T,R).
check([],_).

Solution three:

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

Solution three':

sublist(S,L):-
  append3(_,S,_,L).

Solution

  • ?- phrase((...,seq(Sublist),...),List).
    

    with:

    ... --> [] | [_], ... .
    
    seq([]) --> [].
    seq([E|Es]) --> [E], seq(Es).
    

    (Warning: In order to be able to explain this solution, you need to understand DCGs first!)