Self-test 5, Task 2, Solutions

replace/4

This is an extension of delete_element/3. The key difference is that the replacement element is added as the head of the second list when the element to be replaced is found.
     /* ************************************************ */
     /*                                                  */
     /*   replace/4                                      */
     /*      Arg 1:  Elem1 to be found                   */
     /*      Arg 2:  List1 with Elem1 in                 */
     /*      Arg 3:  Elem2 to be added                   */
     /*      Arg 4:  List2 with Elem2 in                 */
     /*   Summary: True if List2 is List1 with Elem1     */
     /*            substituted by Elem2.                 */
     /*   Author: P J Hancox                             */
     /*   Date:   19 October 1994                        */
     /*                                                  */
     /* ************************************************ */

     % 1 terminating condition
     replace(Elem1, [Elem1|Tail], Elem2, [Elem2|Tail]).
     % 2 recursive
     replace(Elem1, [Head|Tail1], Elem2, [Head|Tail2]) :-
          replace(Elem1, Tail1, Elem2, Tail2).