【问题标题】:OCaml Increment mutable variable several timesOCaml 多次递增可变变量
【发布时间】:2014-04-22 05:11:19
【问题描述】:

问了这么一个小问题,我感到有点羞愧,但我走了。

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

let seed_index = ref 0;;

let incr_seed() = 
    seed_index := !seed_index + 1;;

但是,我无法让它在解释器中工作。

# incr_seed();;
- : unit = ()
# seed_index;;
- : int ref = {contents = 0}

【问题讨论】:

  • 请注意,有一个内置的incr 函数。

标签: ocaml mutable


【解决方案1】:

这应该可行。您确定您向我们展示了所有内容,并且您没有因为在顶层重用定义而感到困惑吗?

混淆自己的一种方法是在定义函数incr_seed 引用先前的seed_index 之后定义一个新的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}

只需退出 OCaml 顶层并从头开始。

【讨论】:

  • 谢谢,我后来在代码中不小心重新定义了seed_index。
猜你喜欢
  • 2019-12-21
  • 1970-01-01
  • 2019-01-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-29
  • 1970-01-01
相关资源
最近更新 更多