Docsity

Final Exam Solution Key - Programming Languages | CSCI 4430, Exams of Programming Languages

Toggle sidebar
bg1
1
Name: SOLUTION KEY
CSCI-4430 Programming Languages
Final Exam, Part I
1 Thread Expressions
Oz provides thread expressions as syntactic sugar for its kernel language
thread statement. The following code is the kernel language version of a
single thread expression.
local R1 R2 in
thread local Ain A=N-1 {Fib A R1} end end
thread local Bin B=N-2 {Fib B R2} end end
{Number.´+´R1 R2 R}
end
Write that thread expression (in as simple a form as you can).
2 pts
Answer:
thread {Fib N-1} end +thread {Fib N-2} end
2 Producer/Consumer Stream Programming
The following code is the same as the Sieve of Eratothenes example (the
original, unoptimized version) discussed in the textbook and one of the
labs, except that the Sieve function is expressed as a procedure instead
of a function.
fun {Generate N Limit}
if N<Limit then
N|{Generate N+1 Limit}
else nil end
end
proc {Sieve Xs R}
case Xs
of nil then R=nil
[] X|Xr then Ys in
{Delay 1}
thread Ys={Filter Xr fun {$ Y} Y mod X \= 0 end}end
local Zin %%
{Sieve Ys Z} %%%% version 1
R=X|Z %
end %%
end
end
% Main program
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe

Partial preview of the text

Download Final Exam Solution Key - Programming Languages | CSCI 4430 and more Exams Programming Languages in PDF only on Docsity!

Name: SOLUTION KEY

CSCI-4430 Programming Languages

Final Exam, Part I

1 Thread Expressions

Oz provides thread expressions as syntactic sugar for its kernel language thread statement. The following code is the kernel language version of a single thread expression.

local R1 R2 in thread local A in A=N-1 {Fib A R1} end end thread local B in B=N-2 {Fib B R2} end end {Number. ´ + ´ R1 R2 R} end

Write that thread expression (in as simple a form as you can).

2 pts

Answer:

thread {Fib N-1} end + thread {Fib N-2} end

2 Producer/Consumer Stream Programming

The following code is the same as the Sieve of Eratothenes example (the original, unoptimized version) discussed in the textbook and one of the labs, except that the Sieve function is expressed as a procedure instead of a function.

fun {Generate N Limit} if N<Limit then N|{Generate N+1 Limit} else nil end end proc {Sieve Xs R} case Xs of nil then R=nil [] X|Xr then Ys in {Delay 1} thread Ys={Filter Xr fun {$ Y} Y mod X = 0 end } end local Z in %% {Sieve Ys Z} %%%% version 1 R=X|Z % end %% end end % Main program

local Xs Ys in thread Xs={Generate 2 10000} end thread Ys={Sieve Xs} end {Browse Ys} end

  1. Rewrite the function call of Sieve in the main program as a procedure call: 1 pt

Answer: {Sieve Xs Ys}

  1. (Circle one) true or false: given that Sieve is now defined as a proce- dure, it is necessary to change all function calls of Sieve (such as the one in the main program) into procedure calls. 1 pt

Answer: False

  1. The local statement containing the recursive call of Sieve could also be written local Z in %% R=X|Z %%%% version 2 {Sieve Ys Z} % end %%

Which version would be produced by Oz in translating the expression X|{Sieve Ys}

into kernel language, (circle one) version 1 or version 2? 1 pt

Answer: Version 2

  1. Which version of Sieve’s definition is iterative, the one with the code in (circle one) version 1 or version 2? Explain. 2 pts

Answer: Version 2 is iterative (uses constant-bounded stack space) because it is tail-recursive.

  1. One version will begin showing the primes immediately, while the other version will not show any output in the Browser (except for an under- score) until the computation is done—which, because of the Delay call, will be more than 10 seconds after computation begins. Which version will begin showing them immediately, (circle one) version 1 or version 2? 1 pt

Answer: Version 2

{WaitAll [ proc {$} {Delay 6000} {Browse a} {Delay 2000} end proc {$} {Delay 2000} {Browse b} end ]} {Browse c}

should display b after about 2 seconds, a after about 6 seconds and c after about 8 seconds. 6 pts Hint: Include in each thread created, as its last statement, a binding of a variable to a value. Then apply Wait to each of the variables, so you set up waiting until all variables used in the threads are bound. If you have trouble programming this for a list of statements, for half credit write a special case procedure WaitThree such that {WaitThree S1 S2 S3} runs S1, S2, and S3 each in its own thread and waits until all three have terminated.

Answer: proc {WaitAll Ps} Ws = {Map Ps fun {$ P} thread {P} true end end } in {ForAll Ws Wait} end

or proc {WaitAll Ps} Ws = {Map Ps proc {$ P W} thread {P} W= true end end } in {ForAll Ws Wait} end

Solution for special case (3 pts credit): proc {WaitThree P1 P2 P3} W1 W2 W3 in thread {P1} W1= true end thread {P2} W2= true end thread {P3} W3= true end {Wait W1} {Wait W2} {Wait W3} end

  1. We’ve also seen a function called WaitTwo, but it has a different mean- ing from a special case of WaitAll. Describe the semantics of the function call {WaitTwo X Y}

where X and Y are variables, as defined in the textbook. 3 pts

Answer: {WaitTwo X Y} suspends until X or Y is bound. If X is bound first, WaitTwo returns 1, and if Y is bound first, WaitTwo returns

  1. Describe a programming situation where you would need WaitTwo. (You may use a situation that occurred in one of the homework prob- lems.) 2 pts

Answer: In the problem of modeling Erlang’s receive expression in Oz, WaitTwo is used to wait for either of two events to occur: timeout or availability of a message in the mailbox stream.

5 Agents With State

Using

fun {NewAgent Process InitState} Port Stream in Port={NewPort Stream} thread Dummy in Dummy={FoldL Stream Process InitState} end Port end

we created a bank account agent abstraction by writing a BankProcess function that we could plug into NewAgent to get a bank account agent able to handle withdrawals, deposits, and balance requests. The state of the agent is the account’s balance, initially 0.

fun {BankProcess S M} case M of withdraw(N) then S-N [] deposit(N) then S+N [] balance(B) then B=S S end end

For example, we can write

BA={NewAgent BankProcess 0} {Send BA deposit(100)} {Send BA deposit(100)} {Send BA withdraw(255)} local B in {Send BA balance(B)} {Wait B} {Show B} end

The balance shown would be negative, because this code doesn’t prevent an overdraft (a withdrawal of more than the current balance). Bob Threadman attempts to solve this problem by programming

6 Erlang Semantics

Suppose an Erlang process executes the following receive expression

receive {public_key_request, From, FromName} -> io:format("Bob: I received a request from ~s for my public key,~n" ++ " which I’ll now grant.~n~n", [FromName]), From! {granted, Public, self(), "Bob"}; Logger! {public_key_request_granted, self(), From}; {secret_key_request, From, FromName} -> io:format("Bob: I received a request from ~s for my secret key.~n" ++ " The nerve!~n~n", [FromName]), From! {no_way, self(), "Bob"}; Logger! {secret_key_request_declined, self(), From} end

  1. Suppose also that the process’s mailbox contains both a secret key request message (sent to the mailbox first) and a public key request message (sent to the mailbox second). According to the semantics of Erlang’s receive expression—which we know well from having modeled it in Oz—which message will be accepted by that receive expression? Circle one: 2 pts

(a) the secret key request (b) the public key request

Answer: secret key request

  1. The message to the Logger process (in either case) is sent (circle one): 2 pts

(a) immediately without waiting for the send of the message back to From to complete (b) only after the send of the message back to From has completed.

(Again, the answer can be deduced from the way we modeled the semantics of Erlang’s message handling in Oz.)

Answer: immediately

7 ADT Implementation Choices

In one of the labs we wrote an implementation called MyArray of an Array ADT in terms of a tuple of cells, with the following interface:

  • A={MyArray.new L H I} returns a new array with indices from L to H, inclusive, all initialized to I.
  • {MyArray.put A I X} puts in A the mapping of I to X.
  • X={MyArray.get A I} returns from A the mapping of I.
  • L={MyArray.low A} returns the lower index bound of A.
  • H={MyArray.high A} returns the higher index bound of A.
  1. Among the choices one has in implementing an ADT are whether to make it stateful or declarative, and whether to make it unbundled or bundled. In this case, these choices are already determined by the problem description. It is

(a) Circle one: stateful vs. declarative. Explain why this is deter- mined by the interface. 3 pts

Answer: Stateful — for it to be declarative MyArray.put would have to return a value (an array). Alternative answer: the prob- lem description mentions that cells are to be used in the imple- mentation.

(b) Circle one: bundled vs. unbundled. Explain why this is deter- mined by the interface. 3 pts

Answer: Unbundled — the data is not kept together with the operations; we have to pass A to each operation.

  1. We discussed one other dimension of choices that one has in imple- menting an ADT. It is vs. 3 pts

Answer: secure vs. open

Final Exam, Part II

8 Parameter Passing Methods

Below are five example programs that model five different parameter passing methods.

  1. Fill in each blank after “Call by” with the name of the parameter pass- ing method that is being modeled in the example code (that follows the blank). Hint: the names of four of the five methods are: value, value-result, reference, name. 5 pts

Answers: value, need, value-result, reference, name

proc {Sqr A} A:=@A*@A end local C={NewCell 0} in C:= {Sqr C} {Browse @C} _% displays:_________ end _%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Call by ______________________

proc {Sqr A} {A}:=@{A}*@{A} end local C={NewCell 0} in C:= {Sqr fun {$} C end } {Browse @C} _% displays:_________ end

  1. C++ provides direct language support for two of these five parameter passing methods. (The other three have to modeled using a combina- tion of other language features.) They are

(a) Call by. 1 pt (b) Call by. 1 pt

Answers: value, reference

9 Reasoning With Explicit State

The following program raises a number to an integer power by a series of multiplications (this is the “naive” algorithm, not the fast “Russian Peas- ant” algorithm in the lecture notes). The beginning of a proof of partial correctness using Hoare-style proof rules is also shown, expressed in the proof tree form presented in a lecture and lab. Complete the proof, using the relevant proof rules presented in the lecture; they are reproduced at the end of the exam. 8 pts

{n >= 0} y := 1; k := 0; {y = x^k and k <= n} while k < n do y:= x*y; k := k+

endwhile {y = x^n} |

| compound

| | {n >= 0} y := x; k := 0; {y = x^k and k <= n+1} |

Answer:

| |while

:=
{n >= 0}

y := x {y = x^k and k <= n and k < n} y = x^k and k <= n {y = x^0 and 0 <= n+1} y := xy; k := k+1 and not(k < n) | {y = x^k and k <= n} implies |:= | y = x^n | |:= | n >=0 | | inequality prop. implies {y = x^k and k <= n and k < n} | x = x^0 and 0 <= n+1 y := xy y = x^k and k = n {y = x^(k+1) and k+1 <= n} implies valid | y = x^n |:= | | | substitution y = x^k and k <= n and k < n | implies y = x^k and k = n xy = x^(k+1) and k+1 <= n} implies | y = x^k |substitution | valid y = x^k and k <= n and k < n implies x(x^k) = x^(k+1) and k+1 <= n}

valid

it may appear that the new transfer method is calling itself recur- sively, but that’s not the case. Name the syntactic unit that transfer(Amt) must parse as in this context:. 1 pt

Answer: term. Alternative answers: record or tuple (technically these are names of Oz data types rather than syntactic categories of the Oz grammar)

  1. Explain why it could not be parsed as a method call instead: 2 pts

Answer: Oz method calls don’t return values, but Oz syntax requires a value for a field of a tuple (the addentry tuple).

  1. There are two other lines of the code where the old or new transfer method is called. One is a static method call and the other is a dynamic method call. Identify them and show which is which by writing “static call” or “dynamic call” in the margin next to the line. 4 pts

Answers: The static call is Account, transfer(Amt) and the dy- namic call is {self transfer(A)}.

  1. Suppose you decide you want only individual amount transfers to be logged, but not batch transfers. Show how you could modify the code to make this change in logging behavior. You should change only one line of code. (Indicate the line you are changing by drawing an arrow to it labeled “changed for question 10-4:” followed by the changed line of code.) 2 pts

Answer: Change the line {self transfer(A)} to Account, transfer(A).

11 Relational Programming in Oz

Suppose we are given

proc {Parent Father Son} choice Father=abe Son=bob [] Father=abe Son=carl [] Father=bob Son=fred [] Father=fred Son=george [] Father=carl Son=howard end end proc {Ancestor X Y} choice {Parent X Y} [] Z in {Parent X Z} {Ancestor Z Y} end end

  1. Find all descendants of Bob. That is, write code that uses Solve and a for loop to browse all solutions X such that 4 pts {Ancestor bob X}

Answer: Solutions={Solve proc {$ X} {Ancestor bob X} end } for S in Solutions do {Browse S} end

  1. Suppose we wish (unconventionally) to redefine the ancestor relation to be reflexive. E.g., we consider the descendants of George to in- clude George himself, and more generally for any person X we consider the descendants of X to include X. Rewrite the Ancestor procedure accordingly. 4 pts

Answer: proc {Ancestor X Y} {Browse "Ancestor"} choice X=Y % the only change is here [] Z in {Parent X Z} {Ancestor Z Y} end end

12 Relational Programming in Prolog

Which of the following descriptions apply to the Prolog language? Circle 8 pts T for true, F for false.

  1. (^) 

 T F Includes lists among its built-in data types.

  1. T (^) 

 F Does not allow new variables to appear in the subgoals of a rule.

  1. (^) 

 T F Uses the closed world assumption.

  1. (^) 

 T F Implements Horn clause logic.

  1. T (^) 

 F Implements a complete logic.

  1. (^) 

 T F Implements a non-monotonic logic.

  1. T (^) 

 F Is both in theory and in practice purely declarative in the (broad) sense of not requiring procedural information in users’ pro- grams.

  1. T (^) 

 F Uses a breadth-first search strategy.