Search code examples
ocamlmutableimperative-programming

OCaml variable, which keeps it value between function calls


Is there a way in OCaml for a variable inside a function to keep its value between function calls? It should work like Pythons default argument, which is a reference to the same object in every function call or the function should rather yield and not explicitly return a value. The effect should be the following (if the function was to return natural numbers):

foo ();;
0
foo ();;
1

Solution

  • Yes this is possible. You need to define a local ref outside of the closure and access its value and modify it every time the closure is used like so:

    let foo =
      (* local variable x *)
      let x = ref 0 in
      (* the closure that will be named foo *)
      fun () -> let r = !x in
                x := r+1; r