Docsity

Polymorphism, Lambda Calculus, and OCaml Modules in Java, Assignments of Programming Languages

Toggle sidebar
bg1
CMSC330 Spring 2008 Homework #1 Solutions
1. (21 pts) OCaml Polymorphic Types
Consider a OCaml module Bst that implements a binary search tree:
module Bst = struct
type bst =
Empty
| Node of int * bst * bst
let empty = Empty (* empty binary search tree *)
let is_empty = function (* return true for empty bst *)
Empty -> true
| Node (_, _, _) -> false
let rec insert n = function (* insert n into binary search tree *)
Empty -> Node (n, Empty, Empty)
| Node (m, left, right) ->
if m = n then Node (m, left, right)
else if n < m then Node(m, (insert n left), right)
else Node(m, left, (insert n right))
(* Implement the following functions
val min : bst -> int
val remove : int -> bst -> bst
val fold : ('a -> int -> 'a) -> 'a -> bst -> 'a
val size : bst -> int
*)
let rec min = (* return smallest value in bst *)
let rec remove n t = (* tree with n removed *)
let rec fold f a t = (* apply f to nodes of t in inorder *)
let size t = (* # of non-empty nodes in t *)
end
a. (3 pts) Is insert tail recursive? Explain why or why not.
No, since the return value for recursive call to insert cannot be used as
the return value of the original call to insert. The return value is used to
create a Node data type first, and the Node value is returned.
b. (3 pts) Implement min as a tail-recursive function. Raise an exception for an
empty bst. Any reasonable exception is fine.
let rec min = function
Empty -> (raise (Failure "min"))
| Node (m, left, right) ->
if (is_empty left) then m
else min left
pf3
pf4
pf5
pf8
pf9
pfa

Partial preview of the text

Download Polymorphism, Lambda Calculus, and OCaml Modules in Java and more Assignments Programming Languages in PDF only on Docsity!

CMSC330 Spring 2008 Homework #1 Solutions

  1. (21 pts) OCaml Polymorphic Types Consider a OCaml module Bst that implements a binary search tree:

module Bst = struct type bst = Empty | Node of int * bst * bst

let empty = Empty (* empty binary search tree *)

let is_empty = function (* return true for empty bst *) Empty -> true | Node (_, _, _) -> false

let rec insert n = function (* insert n into binary search tree *) Empty -> Node (n, Empty, Empty) | Node (m, left, right) -> if m = n then Node (m, left, right) else if n < m then Node(m, (insert n left), right) else Node(m, left, (insert n right))

(* Implement the following functions val min : bst -> int val remove : int -> bst -> bst val fold : ('a -> int -> 'a) -> 'a -> bst -> 'a val size : bst -> int ) let rec min = ( return smallest value in bst ) let rec remove n t = ( tree with n removed ) let rec fold f a t = ( apply f to nodes of t in inorder ) let size t = ( # of non-empty nodes in t *) end

a. (3 pts) Is insert tail recursive? Explain why or why not. No, since the return value for recursive call to insert cannot be used as the return value of the original call to insert. The return value is used to create a Node data type first, and the Node value is returned. b. (3 pts) Implement min as a tail-recursive function. Raise an exception for an empty bst. Any reasonable exception is fine. let rec min = function Empty -> (raise (Failure "min")) | Node (m, left, right) -> if (is_empty left) then m else min left

c. (6 pts) Implement remove. The result should still be a binary search tree. let rec remove n = function Empty -> Empty | Node (m, left, right) -> if m = n then ( if (is_empty left) then right else if (is_empty right) then left else let x = min right in Node(x, left, remove x right) // OR // else let x = max left in // Node(x, remove x left, right) ) else if n < m then Node(m, (remove n left), right) else Node(m, left, (remove n right)) d. (6 pts) Implement fold as an inorder traversal of the tree so that the code List.rev (fold (fun a m -> m::a) [] t) will produce an (ordered) list of values in the binary search tree. let rec fold f a n = match n with Empty -> a | Node (m, left, right) -> fold f (f (fold f a left) m) right e. (3 pts) Implement size using fold. let size t = fold (fun a m -> a+1) 0 t

  1. (36 pts) Recursive Descent Parser in OCaml The example OCaml recursive descent parser 15-parseArith_fact.ml employs a number of shortcuts. For instance, the function parseS handles the grammar rules for S → T + S | T directly instead of first applying left factoring: S → T A A → + S | epsilon However, we can still identify where code corresponding to parseA was inserted directly in the code for parseS, in the comments below: let rec parseS lr = (* parseS ) let x = parseT lr in ( S → T A ) match !lr with ( parseA ) | ('+'::t) -> ( if lookahead = First( + S ) ) lr := t; ( A → + S ) Sum (x,parseS lr) | _ -> x ( A → epsilon *)

Similarly, the function parseF handles the grammar rules for F -> F! | U directly instead of rewriting the grammar, creating the following productions: F ->? B ->? You must identify where code corresponding to parseB was inserted directly in the code for parseF in the comments below: let rec parseF lr = (* parseF *)

  1. (6 pts) Static vs. Dynamic Scoping Consider the following OCaml code. let a = 1 ;; let f = fun ( ) -> a ;; // value of a determined here for static scoping let a = 2 ;; f ( );; // value of a determined here for dynamic scoping a. What value is returned by the invocation of f( ) with static scoping? Explain. 1, since the binding for “a” in the function “f = fun ( ) -> a” refers to the closest lexical value of “a” at the point where the function is declared in the code (1st^ let a). b. What value is returned by the invocation of f( ) with dynamic scoping? Explain. 2, since the binding for “a” in the function “f = fun ( ) -> a” refers to the closest value of “a” in the call stack at the point where the function is actually invoked (2nd^ let a).
  2. (8 pts) Parameter passing Consider the following C code. int i = 2; void foo(int f, int g) { f = f-i; g = f; } int main( ) { int a[] = {2, 0, 1}; foo(i, a[i]); printf("%d %d %d %d\n", i, a[0], a[1], a[2]); } a. (2 pts) Give the output if C uses call-by-value 2 2 0 1, since the call to foo( ) creates 2 local variables f & g (initialized with the values of i & a[i]), and all changes to f & g do not affect i or a[i]. b. (3 pts) Give the output if C uses call-by-reference 0 2 0 0, since the call to foo( ) binds f to i & g to a[2], invoking foo( ) = void foo(f  i, g  a[2]) { f = f – i; // equivalent to i = i – i  i = 0 g = f; // equivalent to a[2] = i  a[2] = 0 } c. (3 pts) Give the output if C uses call-by-name 0 0 0 1, since the call to foo( ) replaces f with i & g with a[i], foo( ) = void foo(f  i, g  a[i]) { f = f – i; // equivalent to i = i – i  i = 0 g = f; // equivalent to a[i] = i  a[0] = 0 }
  3. (10 pts) Polymorphism Consider the following Java classes:

class A { public void a( ) { … } } class B extends A { public void b( ) { … } } class C extends B { public void c( ) { … }} Explain why the following code is or is not legal a. int count(Set s) { … } … count(new TreeSet( )); Legal. Actual parameter type (Set) matches formal parameter type (Set) b. int count(Set s) { … } … count(new TreeSet( )); Illegal. Actual parameter type (Set) is not a subclass of formal parameter type (Set), even though B is a subclass of A. c. int count(Set s) { … } … count(new TreeSet( )); Legal. Type erasure will cause formal parameter type (TreeSet) to become TreeSet, which matches actual parameter type (Set). d. int count(Set s) { … } … count(new TreeSet( )); Legal. Actual parameter type (Set) matches formal parameter type (Set), since? matches A. e. int count(Set s) { … } … count(new TreeSet()); Legal. Actual parameter type (Set) matches formal parameter type (Set), since “? extends A” can match A and its subclasses B & C (classes that extend A, including A) f. int count(Set s) { … } … count(new TreeSet()); Illegal. Actual parameter type (Set) does not match formal parameter type (Set), since “? extends B” can match only B and its subclass C (classes that extend B, including B) g. int count(Set s) { for (A x : s) x.a( ); … } Legal. The actual parameter type (Set) indicates s contains elements of class B or its subclasses. So any element of s may be treated as an object of class B or its subclasses (e.g., C). The for loop treats elements of s as objects of class A, which is a superclass of B, and thus is legal (can use subclass in place of superclass). h. int count(Set s) { for (C x : s) x.c( ); … } Illegal. The actual parameter type (Set) indicates s contains elements of class B or its subclasses. So any element of s may be treated as an object of class B or its subclasses (e.g., C). The for loop treats elements of s as objects of class C, and is illegal since elements of s may be objects of class B (cannot use superclass in place of subclass). i. int count(Set s) { for (A x : s) x.a( ); … } Illegal. The actual parameter type (Set) indicates s contains elements of class B or its superclasses. So any element of s may be treated as an object of class B or its superclasses (e.g., A, Object). The for loop treats elements of s as objects of class A, and is illegal since elements of s may be objects of class Object (cannot use superclass in place of subclass). j. int count(Set s) { for (C x : s) x.c( ); … } Illegal. The actual parameter type (Set) indicates s contains elements of class B or its superclasses. So any element of s may be treated as an object of class B or its superclasses (e.g., A, Object). The for loop

  1. (6 pts) Java multithreading a. Using Java Conditions, you must implement a synchronization construct called MyBarrier. A MyBarrier object is created with a certain value n. When a thread calls the method enter( ), it enters the barrier and blocks until a total of n threads have entered the barrier. When the nth^ threads enters the barrier, all the threads waiting at the barrier wake up and unblock, and the nth^ thread continues without blocking. When a thread calls the method reset( ), the barrier is reset so that it starts fresh in counting up to n (i.e., n more threads must enter the MyBarrier).

public class MyBarrier { int num; // shared read-only data int current = 0; // shared modifiable data Lock lock = new ReentrantLock(); Condition ready = lock.newCondition();

public MyBarrier (int n) { num = n; }

public void enter( ) throws InterruptedException { lock.lock(); // prevent data race on current current++; // incr # of threads at barrier

if (current == num) { // enough threads at barrier ready.signalAll(); // wake up other threads } // continue execution else { while (current < num) { // wait for more threads to enter ready.await(); // sleep until enough threads enter } // use while ( ) in case reset( ) called } lock.unlock(); }

public void reset( ) { lock.lock(); // prevent data race on current current = 0; lock.unlock(); } }

  1. (6 pts) Garbage collection Consider the following Java code. Object a, b, c; public foo( ) { a = new Object( ); // object 1 b = new Object( ); // object 2 c = new Object( ); // object 3 a = b; b = c; c = a; } a. (3 pts) What object(s) are garbage when foo( ) returns? Explain why. Object 1 is garbage there are no longer any references to it within the program. After foo( ) returns, a → object 2, b → object 3, c → object 2. b. (3 pts) Describe the difference between mark-and-sweep & stop-and-copy. Mark-and-sweep stops the program to determine what objects are still reachable. Stop-and-copy in addition will move reachable objects to new locations.
  2. (4 pts) Markup languages a. Creating your own XML tags, write an XML document that organizes the following information: 1-hour test on Spanish Monday in Jiménez worth 15%. 1- hour test on Computers Tuesday in CSIC worth 10%. 30-minute test on Computers Friday in AVW worth 5%.

1 hour Spanish Monday Jiménez 15%

1 hour Computers Tuesday CSIC 10%

30 minute Computers Friday AVW 5%

  1. (24 pts) Lambda calculus Prove the following using the appropriate λ-calculus encodings a. not (not true) = true Given: not = λx.((x false) true) true = λx.λy.x false = λx.λy.y Proof: not (not true) // replacing 1st^ not w/ encoding = λx.((x false) true) (not true) // β-reduction: x → not true = ((not true) false) true // replacing not w/ encoding = ((λx.((x false) true) true) false) true // β-reduction: x → true = (((true false) true) false) true // replace true w/ encoding = ((((λx.λy.x) false) true) false) true // β-reduction: 1st^ x → false = (((λy.false) true) false) true // β-reduction: y → true = ((false) false) true // replace false w/ encoding = ((λx.λy.y) false) true // β-reduction: x → false = (λy.y) true // β-reduction: y → true = true // not (not true) = true b. if false then x else y = y Given: if a then b else c = a b c true = λx.λy.x false = λx.λy.y Proof: if false then x else y // replacing if… w/ encoding = false x y // replacing false w/ encoding = (λx.λy.y) x y // β-reduction: x → x = (λy.y) y // β-reduction: y → y = y // if false then x else y = y c. succ 2 = 3 Given: 2 = λf.λy.f (f y) 3 = λf.λy.f (f (f y)) succ = λz.λf.λy.f (z f y) Proof: succ 2 // replacing succ w/ encoding = (λz.λf.λy.f (z f y)) 2 // β-reduction: z → 2 = λf.λy.f (2 f y) // expanding 2 w/ encoding = λf.λy.f ((λf.λy.f (f y)) f y) // β-reduction: 1st^ f → f = λf.λy.f ((λy.f (f y)) y) // β-reduction: 1st^ y → y = λf.λy.f (f (f y)) // apply encoding for 3 = 3 // succ 2 = 3

d. (* 1 3) = 3 Given: 1 = λf.λy.f y 3 = λf.λy.f (f (f y)) M * N = λx.(M (N x)) Proof: (* 1 3) // replacing * w/ encoding = λx.(1 (3 x)) // replacing 3 w/ encoding = λx.(1 (λf.λy.f (f (f y)) x)) // β-reduction: 1st^ f → x = λx.(1 (λy.x (x (x y)))) // replacing 1 w/ encoding = λx.((λf.λy.f y) (λy.x (x (x y)))) // β-reduction: 1st^ f w/ λy.x (x (x y)) = λx.(λy.(λy.x (x (x y)))) y // β-reduction: 1st^ y → y = λx.λy.x (x (x y)) // α-conversion: replace x with f = λf.λy.f (f (f y)) // apply encoding for 3 = 3 e. (+ 2 1) = 3 Given: 1 = λf.λy.f y 2 = λf.λy.f (f y) 3 = λf.λy.f (f (f y)) M + N = λx.λy.(M x)((N x) y) Proof: (+ 2 1) // replacing + w/ encoding = λx.λy.(2 x)((1 x) y) // replacing 2 w/ encoding = λx.λy.((λf.λy.f (f y)) x)((1 x) y) // β-reduction: 1st^ f → x = λx.λy.(λy.x (x y))((1 x) y) // replacing 1 w/ encoding = λx.λy.(λy.x (x y))(((λf.λy.f y) x) y) // β-reduction: 1st^ f → x = λx.λy.(λy.x (x y))((λy.x y) y) // β-reduction: 3rd^ y → y = λx.λy.(λy.x (x y))(x y) // β-reduction: 2nd^ y → x y = λx.λy.x (x (x y)) // α-conversion: replace x with f = λf.λy.f (f (f y)) // apply encoding for 3 = 3

f. (Y fact) 2 = 2 // you do not need to expand any operators except fact & Y Given: Y = λf.(λx.f (x x)) (λx.f (x x)) fact = λf. λn.if n = 0 then 1 else n * (f (n-1)) Proof: (Y fact) 2 // replacing Y w/ encoding = (λf.(λx.f (x x)) (λx.f (x x)) fact) 2 // β-reduction: 1st^ f → fact = (λx.fact (x x)) (λx.fact (x x)) 2 // β-reduction: 1st^ x → λx.fact (x x) = (fact ((λx.fact (x x)) (λx.fact (x x)))) 2 // apply encoding for (Y fact) // ((λx.fact (x x)) (λx.fact (x x))) → (Y fact) // we know this is the encoding for (Y fact) from 3rd^ line of proof = (fact (Y fact)) 2 // apply encoding for fact