Self-Test 5

Terminate when a specified element is found
 
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 memb_count/2
 
  The procedures memb_count/2 and memb/3 were given in the Module as:
 

     % 1      memb_count(Elem, List) :-           memb(Elem, List, 1).      % 1 terminating condition      memb(Elem, [Elem|_], Cnt) :-           write(Cnt),           nl.      % 2 recursive      memb(Elem, [_|Tail], Cnt) :-           Cnt1 is Cnt + 1,           memb(Elem, Tail, Cnt1).
   
  Add one rule to this procedure that will return the number zero if the list to be searched is empty. Try the following queries to get these solutions:
 

     | ?- memb_count(gamma, [alpha, beta, gamma]).      3      yes      | ?- memb_count(delta, [alpha, beta, gamma]).      no      | ?- memb_count(alpha, []).      0      yes
 
 

Task 2: replace/4
 
  Write a procedure called replace/4 that is true if Elem1 in List1 is replaced by Elem2 to give List2.
 


Your procedure should behave as follows for the given queries:

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

     List = [z,b,c] ? ;

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

     List = [a,b,x] ? ;

     no
     | ?- replace(a, [], z, List).

     no
     | ?- replace(a, List, z, [x,y,z]).

     List = [x,y,a] ? ;

     no
 
 
 

Task 3: insert_after/4
 
  Write a procedure called insert_after/4 that is true if List2 is List1 with Elem1 followed by Elem2.
 


Your procedure should behave as follows for the given queries:

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

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

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

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

     no
     | ?- insert_after(c, [a,b,c,x], x, List).
         
     List = [a,b,c,x,x] ? ;

     no
     | ?- insert_after(a, [], z, List).

     no
     | ?- insert_after(a, List, z, [x,y,a,z]).

     List = [x,y,a] ? ;

     no