Solutions for Sample Questions for Midterm 1 (CS 421 Spring 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?
2. What environment is in effect after each declaration in the code in Problem 1?
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,
iii. tail-recursive.
4. Write an OCAML function pair_up that 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 fold_right : ('a -> 'b -> 'b) -> 'a list -> 'b -> 'b, but without using explicit
recursion, write a function concat : ‘ a list list -> ‘a list that appends all the lists in the
input list of lists, preserving the order of elements. You may use the append function @.
7. Write an Ocaml function list_print : string list -> unit that prints all the strings in a list
from left to right:
a. using tail recursion, but no higher order functions,
b. using fold_left : ('a -> 'b -> 'a) -> 'a -> 'b list -> 'a but no explicit recursion.