Suggested Homework #2 (for Quiz #2 on 01/22/08)
Suppose that the following list of bindings was entered into the OCaml
interpreter in the sequence shown. For each binding, write down :
(a) If the expression is accepted, the value bound ("fn" for functions) and its type,
(b) If the expression is rejected due to a type error, "type error",
(c) If the expression is rejected due to an unbound variable,
the name of the variable that is not bound.
Recall that if a type error occurs, then the variable binding does not
happen. Check your answers by entering this sequence into the interpreter.
In each part below you are required to complete the implementation of a
function by filling in the appropriate expressions in the blanks (parts marked
- let a =
let x = 20 in
let y =
let x = 5 in
x + x
x + y
- let b =
let x = "ab" in
let y = (let x = "cd" in x) ^ x in
x ^ y
- let c =
let x = 22 in
everyOther : 'a list -> 'a list , a function that takes a list and
returns every other element of the list, i.e. the application
everyOther [v1;v2;3;v4;v5;...] evaluates to [v1;v3;v5;...]
let everyOther l =
let rec helper (b,l) =
match l with
 -> ...
| h::t -> if b then ... else ...
zip : 'a list * 'b list -> ('a * 'b) list , a function that
takes two lists (of equal length) and returns a list of pairs of
corresponding elements, i.e. the application
zip ([x1;x2;x3;...;xn],[y1;y2;y3;...;yn]) evaluates to
let rec zip (l1,l2) =
match (l1,l2) with
(,_) -> ...
| (_,) -> ...
| (h1::t1,h2::t2) -> (...) :: (...)
unzip : 'a * 'b list -> ('a list * 'b list ) , a function that
takes a list of pairs and returns two lists (of equal length) of the first
elements of the second elements of the pairs, respectively, i.e. the application
unzip [(x1,y1);(x2,y2);(x3,y3);...;(xn,yn)] evaluates to
let rec unzip l =
match l with
(...) -> (,)
| (...) ->
let ... = ... in