Search code examples
listprolog

Split a list into two in prolog


Im trying to split a list into 2 in prolog. But im still new to this and any help would be much appreciated.

My problem is:

Implement a clause choose(N,L,R,S) that chooses N items from L and puts them in R with the remaining elements in L left in S

This is what i have tried so far:

split(0,_L1,_L2,_L4). 
split(X,[H|T],L1,T):-
     X>0,
     X1 is X-1,
     split(X1,T,[H|L1],T).

When i try to run

split(2,[1,2,4,5],X,Y).
false

This is the result i get. What am i doing wrong?


Solution

  • If X > 0, the first element of the L list must also be the first element of the R list. For example, this should hold: split(1, [a | Rest], [a], Rest). If we want this relationship to hold, we must express it in the head of a rule.

    Your second clause should therefore look more like this:

    split(X, [H|T], [H|L1], Rest) :-
         X > 0,
         X1 is X - 1,
         split(X1, T, L1, Rest).
    

    This splits off the prefix all right, but the rest is not right yet:

    ?- split(2, [1, 2, 4, 5], R, S).
    R = [1, 2|S] ;
    false.
    

    You need to think again about the case where 0 elements are to be split off. What should be the result of split(0, [a, b, c], R, S)?