Solutions for Sample Questions for Midterm (CS 421)
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. 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);;
3. 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);;
Solution:
let rec pair_up f l =
(match l with [] -> []
| x :: xs -> (x, f x))
alternately let pair_up f = map (fun x -> (x, f x))
pair_up : (‘a -> ‘b) -> ‘a list -> (‘a * ‘b) list
a. [(6, 9); (4,7); (1,4)];;
b. type error