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?
2. What environment is in effect after each declaration in the code in Problem 1?
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.
4. Write an OCAML function pair_up takes first a function, then an input list and
returns a list of pairs of an element from input list (the second argument), paired
with the result of applying the first argument to that element. What is the OCAML
type of pair_up? What is the result of the following expressions:
a. pair_up (fun x -> x + 3) [6;4;1];;
b. pair_up ((fun x -> “Hi, “^x), [“John”; “Mary”;“Dana”]);;
c. pair_up (fun x -> x *. 2.0);;
5. Write an Ocaml function palindrome :string list -> unit that first prints the strings
in the list from left to right, followed by printing them right to left, recursing over
the list only once. (Potential extra credit problem: Do this using each of
List.fold_right and List.fold_left but no explicit use of let rec.)
6. Using the rules provided in class, derive a valid type judgment for
let rec fact n = if n = 0 then 1 else let r = fact (n - 1) in n * r;;
(The rules will be provided for you on the exam, if this kind of question is asked.)
7. Write the definition of an OCAML variant type reg_exp to express abstract syntax
trees for regular expressions over a base character set of booleans. Thus, a boolean
is a reg_exp, epsilon is a reg_exp ,the concatentation of two reg_exp’s is a
reg_exp, the “choice” of two reg_exp’s is a reg_exp, and the Kleene star of a
reg_exp is a reg_exp.