Solutions for Sample Questions for Midterm (CS 421 Fall 2006)
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. Given the following OCAML datatype:
type int_seq = Null | Snoc of (int_seq * int)
write a tail-recursive function in OCAML all_pos : int_seq -> bool that returns true if every
integer in the input int_seq to which all_pos is applied is strictly greater than 0 and false
otherwise. Thus all_pos (Snoc(Snoc(Snoc(Null,3),5),7)) should returns true, but
all_pos (Snoc(Null,~1)) and all_pos (Snoc(Snoc(Null, 3),0)) should both return false.
Solution:
let rec all_pos s =
(match s with Null -> true
| Snoc(seq, x) -> if x <= 0 then false else all_pos seq);;