我试图在OCaml中保存一个函数的值,以便下次调用该函数时可以访问。有什么方法可以做到这一点吗?
你不能用函数的方式来做这件事,因为函数不会是纯粹的。
你可以使用 ref
来存储你想要的值,并在函数中进行突变。
例如,这个函数计算的是 a + b + X
,其中 X
每调用一次函数,函数值就增加1。
let my_function =
let saved_value = ref 0 in
fun a b ->
saved_value := !saved_value + 1; (* Increment the value *)
a + b + !saved_value
let () = Printf.printf "First: %d\n" (my_function 1 2) (* 1 + 2 + 1 == 4 *)
let () = Printf.printf "Second: %d\n" (my_function 1 2) (* 1 + 2 + 2 == 5 *)