Reference no: EM132233143
PROJECT
The purpose of this project is for you to continue writing OCaml functions, related mostly to tail recursion.
1. Write two versions, one non-tail-recursive and the other tail-recursive, of the following function.
The function takes as arguments an element x (of any type) and a non-negative integer n, and returns a list of n entries all identical to x. If the function is called with a negative n, an exception is thrown.
For example, replicate x 5;; would produce [x;x;x;x;x].
2. Write two versions, one non-tail-recursive and the other tail-recursive, of the following function.
The function takes as argument a non-negative integer n, and returns the list of increasing positive integers up to n (empty list if n is 0). If the function is called with a negative n, an exception is thrown.
For example, makeList 4;; would produce [1;2;3;4].
3. Write two versions, one non-tail-recursive and the other tail-recursive, of the following function.
The function takes as argument a list, and returns the reversed list. For example, reverse [6;8;2;5];; would produce [5;2;8;6].
4. Complete the following code for the function that takes an integer n as argument, and that returns the list of (prime) divisors for n.
For example, divisors 120;; would produce [2;2;2;3;5].
let divisors n =
if n < 2 then raise (Failure "Number must be > 1")
else
let rec helper testDivisor currentDividend =
if currentDividend = 1 then []
else
5. Complete the following code for the function that takes an integer n as argument, and that returns true or false according to whether n is a prime number or not.
Recall that a number p cannot divide n if p*p > n.
For example, isprime 17;; would produce true, while isprime 20;; would produce false.
let isprime n =
if n < 2 then raise (Failure "Number must be > 1")
else
let rec nHasNoDivisor p =
Note: Do run test your functions in the OCaml toplevel, in your Ubuntu.
Attachment:- assignment.rar