Programming Languages: Final Exam

May 8, 2008

Problem 1 (20 points)

Consider the following pseudo-code in an imperative language:
int p=1;

function f(int n,q) {
  if (n==0) then print(p);
   else g(n,q);
}
   
function g(int n,p) {
  p = 2*p;
  f(n-1,p);
}

main () { f(2,2); }
Assume that the language uses pass by value.

Problem 2 (5 points total)

Problem 3 (15 points)

Problem 4 (20 points)

Problem 5 (15 points)

In Java, suppose that you have written a program that compiles and runs correctly containing the following: You now change the program as follows: you supply f in P with a definition, you change it to a concrete method, and you change P to a concrete class. You make no other changes to the program.

Problem 6 (20 points)


#include 

using namespace std;

template 

T reduce(T f(T X, T Y), T A[], int N, T BASE)
{   for (int i = N-1; i>=0; i--) BASE = f(A[i],BASE);
    return(BASE);
}


int add(int X, int Y) { return(X+Y); }

int main() {
int A[3] = { 1,2,3 };

cout << reduce(add,A,3,0);
cout << "\n";
}

Problem 7 (10 points)

Consider the following fragment of Ada code. There are two resources R1 and R2 to be used (e.g. two peripheral devices). For each resource R, there is a task of type "ResourceManager" that protects access to R. There are two tasks of type "Client" that may use the resources. Assume that there is elsewhere a procedure "RunResource(R)" which is the only way to use resource R. (When RunResource(R) completes, R is no longer in use.)
type Resource is ... 

task type ResourceManager is
  entry AssignResource(R: Resource);
  entry UseResource;
end ResourceManager;

task body ResourceManager is
MyResource : Resource;  -- The resource assigned to this task;
begin accept AssignResource(R : Resource) do
                        MyResource := R; end AssignResource;
      loop 
        accept UseResource do RunResource(MyResource); end UseResource;
      end loop;
end ResourceManager;


R1, R2: Resource;
RM1, RM2 : ResourceManager;

task type Client is end Client;
task body Client is
begin 
  --- Each client calls RM1.UseResourec and RM2.UseResource from time to time.
  --- Each client is in itself sequential; that is, a client does not create subtasks.

end Client;

C1, C2 : Client;

procedure main is
begin RM1.AssignResource(R1);
      RM2.AssignResource(R2);
end main;