Last active
July 26, 2019 06:13
-
-
Save camoy/e52c6c64c3585defd035926fccb24871 to your computer and use it in GitHub Desktop.
Implementation of a return construct in OCaml with exceptions and references.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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