Search code examples
listreplaceprologprolog-dif

replacing list elements in sicstus prolog


I am writing a Prolog predicate that takes arguments (A1, A2, L1, L2) and succeeds if all occurences of A1 within L1 have been changed to A2 in L2.

i.e.:

| ?- replace(a, b, [a], X).
X = [b]

Here's what I've written:

replace(Orig,_,[Other],[Other]) :- Other \== Orig.
replace(Orig,Repl,[Orig],[Repl]).
replace(Orig,Repl,[Other|T1],[Other|T2]) :- Other \== Orig, replace(Orig,Repl,T1,T2).
replace(Orig,Repl,[Orig|T1],[Repl|T2]) :- replace(Orig,Repl,T1,T2).

Now, this works, but seems a bit unelegant. Can there be a more elegant solution?

Thanks.


Solution

  • What about:

    replace(A, B, X, Y) :- ( X == A -> Y = B ; Y = X ).
    

    Example:

    ?- maplist(replace(1,x), [1,2,3], Ls).
    Ls = [x, 2, 3].
    

    It is easy to unfold the maplist/3 call into a recursive predicate if you prefer that.