| 1 |
(* |
| 2 |
* Example of early return implementation taken from |
| 3 |
* http://ocaml.janestreet.com/?q=node/91 |
| 4 |
*) |
| 5 |
|
| 6 |
let with_return (type t) (f : _ -> t) = |
| 7 |
let module M = |
| 8 |
struct exception Return of t end |
| 9 |
in |
| 10 |
let return = { return = (fun x -> raise (M.Return x)); } in |
| 11 |
try f return with M.Return x -> x |
| 12 |
|
| 13 |
|
| 14 |
(* Function that uses the 'early return' functionality provided by `with_return` *) |
| 15 |
let sum_until_first_negative list = |
| 16 |
with_return (fun r -> |
| 17 |
List.fold list ~init:0 ~f:(fun acc x -> |
| 18 |
if x >= 0 then acc + x else r.return acc)) |