ocaml - 没有args和全局变量的函数

Gre*_*reg 2 variables ocaml global

我有一个任务要做ocaml并且找不到任何帮助信息所以请问这里;)如何定义在不使用全局变量的情况下在每次调用中给我们其他东西的函数?我想做的有趣的是next()返回下一个奇数或下一个阶乘值.

像这样

# next();;
- : int = 1
# next();;
- : int = 3
# next();;
- : int = 5
# next();;
- : int = 7
Run Code Online (Sandbox Code Playgroud)

你有什么提示吗?

提前致谢

格雷格

gas*_*che 5

let next =
  let private_counter = ref (-1) in
  fun () ->
    private_counter := !private_counter + 2;
    !private_counter
Run Code Online (Sandbox Code Playgroud)

您也可以将其封装在"柜台工厂"中:

let make_counter () =
  (* note the () parameter : at each call of make_counter(),
     a new "next function" with a fresh counter is generated *)
  let private_counter = ...
Run Code Online (Sandbox Code Playgroud)