Coderman
Coderman

Reputation: 161

How to make a sublist in Prolog

How would I do this in prolog?

I have already got this to make a sublist, but now need to make sure the first and last element of the second list are not included in the first list.

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

Upvotes: 1

Views: 436

Answers (2)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476574

You can use pattern matching such that the head and the tail are non-empty:

sublist(S,L) :-
    append([_|_],L2,L),
    append(S,[_|_],L2).

In the first append/3 we thus ensure that the part before the sublist is non-empty, and in the second append/3 we ensure that the part after the sublist is non-empty.

Upvotes: 2

Reema Q Khan
Reema Q Khan

Reputation: 878

Here is my approach:-

    sub([],[]).
    sub(S,A):- 
        append(_L1,L2,A),
        append(S1,_L3,L2),
        removefirstelement(S1,S2),
        removelastelement(S,S2).
    
    removefirstelement([_|T],T).
    removelastelement([],[_]).
    removelastelement([X|Xs], [X,Next|T]) :- 
        removelastelement(Xs, [Next|T]).

?-sub(S,[a,b,c,d,e]).
S = []
S = [b]
S = [b, c]
S = [b, c, d]
S = []
S = [c]
S = [c, d]
S = []
S = [d]
S = []

Just add the removefirstelement and removelastelement predicates.

Upvotes: 1

Related Questions