Skip to content

Instantly share code, notes, and snippets.

@camoy
Last active July 26, 2019 06:13
Show Gist options
  • Save camoy/e52c6c64c3585defd035926fccb24871 to your computer and use it in GitHub Desktop.
Save camoy/e52c6c64c3585defd035926fccb24871 to your computer and use it in GitHub Desktop.
Implementation of a return construct in OCaml with exceptions and references.
let with_return f x =
let r = ref None in
try
f (fun v -> r := (Some v); raise Not_found) x
with _ ->
match !r with
| None -> raise Not_found
| Some x -> x
let til_first_even =
with_return (fun return xs ->
List.iter (fun x ->
if x mod 2 = 0 then
return x
else
print_int x; print_string ",") xs;
-1)
let _ =
print_int (til_first_even [1; 3; 5; 8; 17; 21]);
print_string "!\n"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment