File: let_try.ml

package info (click to toggle)
ocaml-benchmark 1.7-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 300 kB
  • sloc: ml: 1,114; makefile: 45; perl: 12
file content (30 lines) | stat: -rw-r--r-- 660 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
(* Compare two possible implementations of let try x = ... with ... *)

let k x = if x >= 0 then x else failwith "x < 0"

let f a =
  let sgn s x =
    let y = (try Some(k x) with _ -> None) in
    match y with
    | None -> s
    | Some y -> s + y in
  ignore(Array.fold_left sgn 0 a)

let g a =
  let sgn s x =
    (try
       let y = k x in
       (fun () -> s + y)
     with _ ->
       (fun () -> s)
    )() in
  ignore(Array.fold_left sgn 0 a)


open Benchmark

let () =
  let a = Array.init 1000 (fun _ -> Random.int 2 - 1) in
  let res = throughputN ~repeat:5 1 [("Some", f, a);
                                     ("()->", g, a); ] in
  tabulate res