Self-Test 6

Terminate when a specified position is reached
 
Where the question includes a partial program, you are advised to copy and paste this into a file. You should develop all your solutions on a machine and test them before looking at the solutions.

Task 1: adding to position/3
 
  The procedure position/3 was given in the Module as:
 

     % 1 terminating condition      position(1, Elem, [Elem|_]).      % 2 recursive      position(Cnt, Elem, [_|Tail]) :-           Cnt1 is Cnt - 1,           position(Cnt1, Elem, Tail).
   
  Add one clause to this procedure for which the position is zero if the list to be searched is empty. Try the following queries to get these solutions:
 

     | ?- position(0, Elem, []).      true ? ;      no      | ?- position(2, Elem, [a,b,c]).      Elem = b ? ;      no      | ?- position(4, Elem, [a,b,c]).      no
 
 

Task 2: replace_at_pos/4
 
  Write a procedure called replace/4 that is true if an element in List1 at position Pos is replaced by Elem to give List2.
 


Your procedure should behave as follows for the given queries:

     | ?- replace_at_pos(1, z, [a,b,c], List).

     List = [z,b,c] ? ;

     no
     | ?- replace_at_pos(3, x, [a,b,c], List).

     List = [a,b,x] ? ;

     no
     | ?- replace_at_pos(0, z, [], List).

     no
     | ?- replace_at_pos(3, Elem, [x,y,z], [x,y,a]).

     Elem = a ? ;

     no
 
 

Task 3: insert_before_pos/4
 
  Write a procedure called insert_before_pos/4 that is true if List2 is List1 with Elem1 preceded by Elem.
 


Your procedure should behave as follows for the given queries:

     | ?- insert_before_pos(1, z, [a,b,c], List).

     List = [z,a,b,c] ? ;

     no
     | ?- insert_before_pos(3, x, [a,b,c], List).

     List = [a,b,x,c] ? ;

     no
     | ?- insert_before_pos(3, c, List, [a,b,c,x]).

     List = [a,b,x] ? ;

     no
     | ?- insert_before_pos(0, z, [], List).

     no