2.
module Complex = struct
type num = {real: int; img: int}
let add c1 c2 = {real = (c1.real + c2.real); img = (c1.img + c2.img)}
let sub c1 c2 = {real = (c1.real - c2.real); img = (c1.img - c2.img)}
let mul c1 c2 = {real = ((c1.real * c2.real) – (c1.img * c2.img)); img = ((c1.real * c2.img) +
(c2.real * c1.img))}
end
---------------------------------------------------------------------------
2.2
The first one [ref 5; ref 5] is a list of 2 different references, and the second one is a list of 2
same references let x = ref 5 in [x;x]
-------------------------------------------------------------------------
3.1
A functor is a higher order module that takes one or more modules as input and returns a
new module as output. It is important in that it allows for code reusability; it abstracts away
implementation details and allows generalized designs.
-------------------------------------------------------------------------
3.2
Yes. The ‘a ref types are considered mutable in that they allow for the value stored in
memory to be mutated. While the ref variables themselves are not mutable and will always
hold the same address location, the value stored in that address is mutable.
-----------------------------------------------------------------------
4.1
let rec from n = Cons(n, fun () -> from(n*2))
let pow2 = form 1
---------------------------------------------------------------------
4.2
Let rec from n = Cons((if(n mod 3 = 0) then ‘a’ else if (n mod 3) then ‘b’ else ‘c’), fun()->
from(n+1))
let abc = from 0
----------------------------------------------------------------
5.1
1;
type ‘a seq = Cons of (‘a * (unit -> ‘a seq))
2;
let hd (Cons(h,t)) = h
let tl (Cons(h,t)) = t ()
let rec map seq f = Cons((f (hd seq)), fun () -> map (tl seq) f)
3;
let rec form f x = Cons(x, fun()-> from f (f x))
---------------------------------------------------------------
6.1
1;
let clip x = if(x<1) then 1 else if(x>10) then 10 else x
2;
let cliplist lst = List.map clip lst
3;
let mapl f lst = List.map (List.map f ) lst
---------------------------------------------------------------
7.1
1;
let hd (Cons(h,t)) = h
let tl (Cons(h,t)) = t ()
let rec filter seq p = if (p (hd seq)) then Cons((hd seq), fun()-> filter (tl seq) p) else filter (tl
seq) p
2;
let rec interleave seq1 seq2 = Cons((hd seq1), fun()->
Cons((hd seq2), fun()-> Interleave (tl seq1) (tl seq2))
----------------------------------------------------------
7.2
1;
module Maybe = struct
let fmap f = function
| Some x -> Some (f x)
|None -> None
let join = function
|Some (Some x) -> Some x
|Some None -> None
|None -> None
end
2;
module Maybe: Monad =
type ‘a t = ‘a option
let return x = Some x
….. Sorry I can’t code this question…….