Search code examples
prolog

included_list(List1, List2)


included_list is true when list1 is part of list2.

For example,

included_list([1,2],[1,2,3,4]) is true. 
included_list([2,1],[1,2,3,4]) is false.
included_list([],[1,2,3,4]) is false.
included_list([1,1,1,1,1,1],[1,2,3,4]) is false.

What predicate should I write in order to get this answers?

I have tried this:

included_list([Head],List).

included_list([Head1|Tail1],[Head2|Tail2]) :-
                    member(Head1,[Head2]),included_list(Tail1, Tail2).

But it returns true when I ask included_list([1,1,1,1,1,1],[1,2,3,4])

If it is possible I want to do it without built-in libraries.


Solution

  • starts_with([H], [H|_]).
    starts_with([H|T1], [H|T2]) :- starts_with(T1, T2).
    
    included_list(X, Y) :- starts_with(X, Y).
    included_list(X, [_|T]) :- included_list(X, T).
    

    Tests:

    ?- included_list([], [1, 2, 3, 2, 1]).
    false.
    
    ?- included_list([2, X], [1, 2, 3, 2, 1]).
    X = 3 ;
    X = 1 ;
    false.
    

    Version 2, riffing off @rajashekar's code:

    included_list([X|Y], L2) :- append(T, _, L2), append(_, [X|Y], T).