Sample Midterm1 Sol-fa07 - Sample Questions for Midterm 1...

Info iconThis preview shows pages 1–3. Sign up to view the full content.

View Full Document Right Arrow Icon
Sample Questions for Midterm 1 (CS 421 Fall 2007) On the actual midterm, you will have plenty of space to put your answers. Some of these questions may be reused for the exam. 1. Given the following OCAML code: let x = 3;; let f y = x + y;; let x = 5;; let z = f 2;; let x = “hi”;; What value will z have? Will the last declaration ( let x = “hi”; ) cause a type error? What is the value of x after this code has been executed? Solution: z is bound to 5 let x = “hi” will not cause a type error x is bound to “hi” 2. What environment is in effect after each declaration in the code in Problem 1? Solution: let x = 3;; {x 3} let f y = x + y;; {f <y x+y, {x 3}>, x 3} let x = 5;; {x 5} + {f <y x+y, {x 3}>, x 3} = {x 5, f <y x+y, {x 3}>} let z = f 2;; {z 5, x 5, f <y x+y, {x 3}>} let x = “hi”;; {x “hi”} + {z 5, x 5, f <y x+y, {x 3}>} = {x “hi”, z 5, f <y x+y, {x 3}>} 3. Consider the following two OCaml functions, loop1 and loop2 : let rec loop1 () = loop1(); () let rec loop2 () = loop2();; val loop1 : unit -> unit = <fun> val loop2 : unit -> ’a = <fun> Suppose you were to run loop1();; and loop2();; in OCaml, (pressing CTRL + C after at least a minute to terminate infinite loops when necessary). a. For each program, what behavior would you expect to see? b. What is the difference between loop1 and loop2? c. For each program state if it is: i. recursive, ii. forward recursive,
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
iii. tail-recursive. Solution: a. The first program generates a stack overflow, while the second program runs indefinitely. b. Both programs are recursive, and in fact forward recursive, but loop2 is tail- recursive while loop1 is not. c. Because loop1 is not tail-recursive, each new recursive call must push a new activation record onto the stack, hence the stack overflow, but since loop2 is tail- recursive, each new activation record may overwrite the previous call, and thus the
Background image of page 2
Image of page 3
This is the end of the preview. Sign up to access the rest of the document.

This test prep was uploaded on 04/21/2008 for the course CS 421 taught by Professor Kamin during the Fall '08 term at University of Illinois at Urbana–Champaign.

Page1 / 5

Sample Midterm1 Sol-fa07 - Sample Questions for Midterm 1...

This preview shows document pages 1 - 3. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online