Sam R
Sam R

Reputation: 31

Prolog recursive list split

I'm new to Prolog and I'm having trouble with the first part of my programming assignment: Create a predicate split that that takes as input three parameters. The first and third parameters are lists and the second parameter is an element. You can think of the first parameter as being the input and the last two parameters being the output. The method computes all possible way of splitting a list into an element and the rest of the list. Here is an example run.

?- split([1,2,3,4,5],X,Y).
X = 1,
Y = [2, 3, 4, 5] ;
X = 2,
Y = [1, 3, 4, 5] ;
X = 3,
Y = [1, 2, 4, 5] ;
X = 4,
Y = [1, 2, 3, 5] ;
X = 5,
Y = [1, 2, 3, 4] ;

There are two rules in defining the predicate. The first rule simply gets the first element of the list and returns it as the second parameter and the rest of the list as the third parameter. The second rule generates the list by copying the first element of the list in the result (i.e., third parameter) and then recursively applying the method to the rest of the elements.

Upvotes: 0

Views: 1127

Answers (2)

SQB
SQB

Reputation: 4078

split([H|T], H, T).

split([H|T], X, [H|Y]) :-
    split(T, X, Y).

There are two ways to take an element out of a list:

  1. Take the head (the first element)
  2. Set the head aside and take an element out of the tail (the rest of the list)

Notice that the predicate can run both ways; if the second and the third parameters are defined, it will yield all possible ways these two can be combined to form a list.

Upvotes: 2

Ans Piter
Ans Piter

Reputation: 573

split(List,Elem,Rest) :- select(Elem,List,Rest).

| ?- select(X,[1,2,3],Y).
X = 1,
Y = [2,3] ? ;
X = 2,
Y = [1,3] ? ;
X = 3,
Y = [1,2] ? ;
no

and with split/3 ;

| ?- split([1,2,3,4],X,Y).
X = 1,
Y = [2,3,4] ? ;
X = 2,
Y = [1,3,4] ? ;
X = 3,
Y = [1,2,4] ? ;
X = 4,
Y = [1,2,3] ? ;
no

with Sicstus-prolog u need to export select from library/lists

:- use_module(library(lists)).

Upvotes: 1

Related Questions