I feel slightly ashamed for asking such a trivial question but here I go.
I need a function to increment a globally defined mutable variable.
let seed_index = ref 0;;
let incr_seed() = 
    seed_index := !seed_index + 1;;
However, I can't get it to work in the interpreter.
# incr_seed();;
- : unit = ()
# seed_index;;
- : int ref = {contents = 0}
This should work. Are you sure you are showing us everything and you did not confuse yourself by re-using definitions in the toplevel?
One way to confuse oneself is to define a new seed_index after the function incr_seed has been defined referring to a previous seed_index. This amounts to:
let seed_index = ref 0;; (* first definition *)
let incr_seed() = 
    seed_index := !seed_index + 1;;
let seed_index = ref 0;; (* second definition *)
incr_seed();; (* this calls a function that refers to the first seed_index *)
seed_index;; (* this displays the second seed_index *)
- : int ref = {contents = 0}
Just quit the OCaml toplevel and restart from scratch.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With