Skip to content

Instantly share code, notes, and snippets.

@podhmo
Created April 11, 2015 17:17
Show Gist options
  • Save podhmo/668a08b7162c24a42dd4 to your computer and use it in GitHub Desktop.
Save podhmo/668a08b7162c24a42dd4 to your computer and use it in GitHub Desktop.
module type Number = sig
type t
val (+) : t -> t -> t
val (/) : t -> t -> t
val of_int : int -> t
val init : unit -> t
end
module Make = functor
(N : Number) ->
struct
let sum arr =
let open N in
let r = ref @@ init () in
for i = 0 to (Array.length arr) - 1 do
r := !r + arr.(i)
done;
!r
let ave arr =
let s = sum arr in
N.(/) s (N.of_int @@ Array.length arr)
end
module Float = struct
type t = float
let (+) x y = x +. y
let (/) x y = x /. y
let init () = 0.0
let of_int x = float x
end
module FCal = Make(Float)
let main () =
let arr = [|2.1; 2.2; 2.3|]
in
Printf.printf "%f\n" @@ FCal.ave arr
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment