Self-test 6, Task 2, Solutions

replace_at_pos/4

This is an extended version of delete_nth/3:
     /* ************************************************ */
     /*                                                  */
     /*   replace_at_pos/4                               */
     /*      Arg 1:  Counter: integer                    */
     /*      Arg 2:  Elem to be added                    */
     /*      Arg 3:  List1 with old element in           */
     /*      Arg 3:  List2 with Elem added               */
     /*   Summary: is true if List2 is List1 with Elem   */
     /*            at the nth position.                  */
     /*   Author: P J Hancox                             */
     /*   Date:   21 October 1994                        */
     /*                                                  */
     /* ************************************************ */

     % 1 terminating condition
     replace_at_pos(1, Elem, [_|Tail], [Elem|Tail]).
     % 2 recursive
     replace_at_pos(Pos, Elem, [Head|Tail1], [Head|Tail2]) :-
          Pos1 is Pos - 1,
          replace_at_pos(Pos1, Elem, Tail1, Tail2).