Computing Real-Valued Vector l2-norm in OCaml Example
Recall that the -norm of a real-valued vector is
where is the -th component of . Implement an OCaml function l2_norm : float list -> float
such that l2_norm x
is the -norm of x
.
Solution
To solve this problem, we need a way to compute the iterated sum and then pass the result to the standard library's Float.sqrt : float -> float
function. We can use the higher-order function List.fold_left : ('b -> 'a -> 'b) -> 'b -> 'a list -> 'b
to traverse the list from left to right while accumulating the sum of squares.
ocaml
let l2_norm : float list -> float =
fun x ->
Float.sqrt (List.fold_left (fun acc comp -> acc +. comp *. comp) 0. x)