ocaml.ml 539 B

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