Split into two a list from a point or character - Prolog?

0

I want to develop the following exercise in Prolog .

I have a list

Lista = [a,b,c,d,f,g,h,i]

and I want to split it in two when I find for example the character ' d ' so the result would be the same:

L1 = [a,b,c]
L2 = [f,g,h,i]

I appreciate your help.

    
asked by Yulian David 07.10.2017 в 16:13
source

1 answer

1

If the head of the list unifies with the wanted element, the empty list is returned as the left list, and the rest of the list (the queue) as the right list:

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

Finally, we recursively search the list's queue and add the current head to the resulting left list:

split([H|T],E,[H|F],S) :- split(T,E,F,S).

For example:

?- split([a,b,c,d,e,f,g], d, X, Y).
   X = [a,b,c] , Y = [e,f,g] ;
   false.

?- split([a,b,c,d,e,d,g], d, X, Y).
   X = [a,b,c] , Y = [e,f,g] ;
   X = [a,b,c,d,e] , Y = [g] ;
   false.

?- split([a,b,c], d, X, Y).
   false.
    
answered by 09.10.2017 / 13:28
source