OCaml多次递增可变变量

use*_*773 3 ocaml mutable

对于提出这样一个微不足道的问题我感到有点惭愧,但在这里我走了.

我需要一个函数来增加一个全局定义的可变变量.

let seed_index = ref 0;;

let incr_seed() = 
    seed_index := !seed_index + 1;;
Run Code Online (Sandbox Code Playgroud)

但是,我无法让它在翻译中工作.

# incr_seed();;
- : unit = ()
# seed_index;;
- : int ref = {contents = 0}
Run Code Online (Sandbox Code Playgroud)

Pas*_*uoq 5

这应该工作.你确定你向我们展示了所有东西,并且你没有通过重新使用顶层中的定义来混淆自己吗?

混淆自己的一种方法是在参考前一个seed_index函数incr_seed定义函数后定义一个新函数seed_index.这相当于:

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}
Run Code Online (Sandbox Code Playgroud)

只需退出OCaml顶级并从头开始重启.