Assignment 1, CSC429, Spring 2009
These are some warm-up exercises, to help you get used to programming in OCAML.
1 Test Cases
You must have test cases for each function; each test case should be an expression that produces true if the test case passes, and false if it fails. Ideally, it will also print a message when a test case fails.
2 OCaml’s if
In order to complete some of the problems here, you’ll need to use OCaml’s if, which won’t be too surprising except that it requires an explicit then:
So, for instance, these two expressions:
if (3 > 4) |
then 15 |
else 156;; |
|
if true |
then "abc" |
else "def";; |
# - : int = 156 |
# - : string = "abc" |
3 Recursion:
In order to make an OCaml function recursive, you must declare it with "let rec", rather than "let".
So, for instance, here’s an infinite loop (with a call to it):
let rec loop x = loop x;; |
|
(loop "dontcare");; |
4 Problems:
Develop the function f1 with type (float -> float) defined by this equation: f1 (x) = 3x^2 + 14.
Develop the function f2 with type (float -> float) defined by this equation: f2 (x) = x^3 + 2x^2
Develop the function differ, that consumes a function and a value for x and produces an approximation of the value of the function’s first derivative at that point, by using the value of f at x and at x + (sqrt epsilon_float).
Develop the function oneStep, that consumes a float and either increases it by 1 percent or decreases it by 1 percent, depending on the result of (Random.random ()). Writing a test case for this is tricky. Do your best.
Develop the function nSteps, that consumes a float and an int >= 0 and returns the result of applying the oneStep function n times. Again, give some thought to a reasonable test case.