Skip to content

Instantly share code, notes, and snippets.

@Octachron
Last active March 18, 2025 16:55
Show Gist options
  • Save Octachron/dcec90617ce49ced058924bf2b96e515 to your computer and use it in GitHub Desktop.
Save Octachron/dcec90617ce49ced058924bf2b96e515 to your computer and use it in GitHub Desktop.
let w = Weak.create 2
let gen () =
let x = "Hello" ^ string_of_int (Random.int 50) in
Weak.set w 0 (Some x);
let f () = () in
Gc.finalise_last (fun () -> ignore (Sys.opaque_identity x)) f;
f
let forgetful_gen2 () =
let x = "world" ^ string_of_int (Random.int 50) in
Weak.set w 1 (Some x);
let f () = () in
f
let () =
let f = gen () in
let g = forgetful_gen2 () in
Gc.compact ();
begin match Weak.get w 0 with
| None -> Format.printf "Forgotten@."; assert false
| Some x -> Format.printf "Remembered %s@." x
end;
begin match Weak.get w 1 with
| None -> Format.printf "Forgotten@."
| Some x -> Format.printf "Remembered %s@." x; assert false
end;
f (); g ()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment