user12379114
user12379114

Reputation:

How can I see if a function has already been called in OCaml?

I'm trying to save a value in a function in OCaml that I can then access the next time the function is called. Is there a way to do this?

Upvotes: 0

Views: 57

Answers (1)

Artyer
Artyer

Reputation: 40911

You can't do this in a functional way, as the function would not be pure.

You can use a ref to store the value you want, and mutate it in the function.

For example, this function that computes a + b + X, where X increases by 1 every time the function is called:

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 *)

Upvotes: 1

Related Questions