2
votes

Hello is there any way to separate a list in Prolog into two other lists, the first includes everything before an element and the second everything after the element. For example

A=[1,2,3,5,7,9,0] and element=5 

the two lists should be

A1=[1,2,3] and A2=[7,9,0]

I don't care about finding the element just what to do next

2

2 Answers

2
votes

it's easy as

?- Elem = 5, A = [1,2,3,5,7,9,0], append(A1, [Elem|A2], A).

edit to explain a bit...

append/3 it's a relation among 3 lists.

It's general enough to solve any concatenation on proper lists - when not there are circular arguments.

The comparison it's a plain unification, that take place on second argument. That must be a list beginning with Elem. Prolog list constructor syntax is [Head|Tail]. To make unification succeed, Elem must match the Head.

2
votes

Here's an alternative method, illustrating how to handle it with list recursion:

split([E|T], E, [], T).
split([X|T], E, [X|LL], LR) :-
    X \== E,
    split(T, E, LL, LR).

Or better, if your Prolog supports dif/2:

split([E|T], E, [], T).
split([X|T], E, [X|LL], LR) :-
    dif(X, E),
    split(T, E, LL, LR).

Examples:

| ?- split([1,2,3,4,5], 3, L, R).

L = [1,2]
R = [4,5] ? ;

no
| ?- split([1,2,3,4,5], 5, L, R).

L = [1,2,3,4]
R = [] ? ;

(1 ms) no
| ?- split([1,2,3,4,5], 1, L, R).

L = []
R = [2,3,4,5] ? ;

no
| ?-

It is a sort of specialized twist on append/3 as CapelliC showed.