2
votes

I have two prolog predicates that perform very similar functions, and I would like to make them into one to simplify things. These are the predicates:

join(DELIM, [X|XS], RESULT) :-
    join(DELIM, XS, RXS),
    append([X, DELIM, RXS], RESULT).
join(DELIM, [END], END).

split(DELIM, [X|XS], RESULT) :-
    append([X, DELIM, RXS], RESULT),
    split(DELIM, XS, RXS).
split(DELIM, [END], END).

The first takes a delimiter and a list of lists, and joins them together using the delimiter. The other does the opposite, splitting one list into a list of other lists based on a delimiter. Even though their arguments are in the same places, if I try to interchange them, they will not work. If at all, how can I make these two predicates into one?

1
They're not functions in Prolog. They're predicates. - lurker

1 Answers

1
votes

append/2 seems viable:

delim(D, Xs, [Ls|Ys]) :-
    append([Ls, D, Rs], Xs),
    delim(D, Rs, Ys).
delim(_, Xs, [Xs]).

?- delim([x],[1,x,2,3,x,4],R).
R = [[1], [2, 3], [4]] ;
...

?- delim([x],Xs,[[1], [2, 3], [4]]).
Xs = [1, x, 2, 3, x, 4] 
.

beware: could be not universally terminating :-)