Cornell cs3110 - Chapter7 Exercises
(* Exercise: mutable fields *)
type student = {
name : string;
mutable gpa : float;
}
let stuA = {name = "Alice"; gpa = 3.7}
let () = stuA.gpa <- 4.0
(* Exercise: int fun *)
let inc = ref (fun x -> x + 1)
let num = !inc 3109
(* Exercise: addition assignment *)
let ( +:= ) x y = x := !x + y
(* Exercise: norm )
( AF: the float array [| x1; ...; xn |] represents the
-
vector (x1, ..., xn)
- RI: the array is non-empty *)
type vector = float array
let norm v = Array.map (fun x -> x *. x) v |> Array.fold_left ( +. ) 0. |> sqrt
(* Exercise: normalize *)
let normalize v =
let n = norm v in
Array.iteri (fun i x -> v.(i) <- x /. n) v
(* Exercise: norm loop *)
let norm_loop v =
let n = ref 0. in
for i = 0 to Array.length v - 1 do
n := !n +. v.(i) *. v.(i)
done;
sqrt !n
(* Exercise: normalize loop *)
let normalize_loop v =
let n = norm_loop v in
for i = 0 to Array.length v - 1 do
v.(i) <- v.(i) /. n
done
(* Exercise: init matrix *)
let init_matrix n o f =
Array.init n (fun i -> Array.init o (fun j -> f i j))