COMP 3958: Lab 1
Put your implementation in a file named lab1.ml. Be sure to test your functions in utop. Note that you
may need to implement helper functions. Provide comments to indicate what each function does. Your file
must compile. If it does not, you may receive no credit for this lab exercise. Maximum score: 12.
1. Implement the following functions with the given signatures using recursion and without calling any
function from the library. Provide tail-recursive versions if possible. You may implement additional
helper functions if needed.
(a) val drop-while:
(‘a -> b001)
drop_while f lst returns a copy of 1st with leading elements satifying f (i.e., element e where
f e returns true) dropped. For example,
drop_while (fun x
-› x mod 2 = 0) [4;2;6;7;6;8;1] returns [7;6;8;1]
Note that in the example, leading even integers are dropped.
(b) val mapi:
-› ‘a list -> ‘b list
mapi is basically the same as the map function we saw in class, except that the function it takes
(with type int -> ‘a -> ‘b) is applied to the index of the element as first argument (counting
from 0), and the element itself as second argument. For example,
mapi (fun i x
-› (i, x)) [“hello”; “cruel”; “world”] returns [(0, “hello”);
(1, “cruel”); (2,
“world”) ]
(c) val unzip
›a list * ‘b list
unzip is like the reverse of zip; it takes a list 1st of pairs and returns a pair of lists where the
first list consists of the first element of each pair in 1st and the second list consists of the second
element of each pair in 1st. For example,
unzip [(1,’a’); (2,’b’); (3,’ c’)] returns ([1; 2; 3], [‘a’; ‘b’; ‘c’])
(d) val dedup:
dedup 1st returns a list where all consecutive duplicated elements in 1st are collapsed into
single element. (Assume that the type of elements supports comparison using the = operator.)
For example,
dedup [1; 1; 2; 3; 3; 3; 2; 1; 1] returns [1; 2; 3; 2; 1]
2. The exponential function can be defined by the infinite series
exp(2) =1+2+y+
Implement a function exp x n
-> float from basics that returns the sum of the
first n+1 terms of the above series, i.e., it returns the sum
Evaluate exp 1.0 20 to find an approximate value of e which is defined as e = exp(1).
(Do not use any library function except for float_of_int.)