Let's keep it simple and use append/3
, meta-predicate maplist/2
and prolog-dif like so:
item_following_in_inserted(I,J,Xs,Ys) :-
append(Prefix,[J |Suffix],Xs),
maplist(dif(J),Prefix),
append(Prefix,[J,I|Suffix],Ys).
Done! It's query time... First, let's run the query the OP gave:
?- item_following_in_inserted(5,10,[2,4,10,12],Xs).
Xs = [2,4,10,5,12] % succeeds, but leaves behind choicepoint
; false.
What if the item is not a member of the given list?
?- item_following_in_inserted(5,10,[2,4, 12],Xs).
false. % fails, as expected: 10 is absent
Let's check that we only insert after the first occurrence—and nowhere else!
?- item_following_in_inserted(5,10,[2,4,10,12,10],Xs).
Xs = [2,4,10,5,12,10] % single solution
; false. % terminates universally
What about the most general query of item_following_in_inserted/4
?
?- item_following_in_inserted(I,E,Xs,Ys).
Xs = [ E|_Z], Ys = [ E,I|_Z]
; Xs = [ _A,E|_Z], Ys = [ _A,E,I|_Z], dif(E,_A)
; Xs = [ _A,_B,E|_Z], Ys = [ _A,_B,E,I|_Z], dif(E,_A), dif(E,_B)
; Xs = [_A,_B,_C,E|_Z], Ys = [_A,_B,_C,E,I|_Z], dif(E,_A), dif(E,_B), dif(E,_C)
...