0

I would like to write a minimal function with an internal state. It should have signature f: () -> () and the n-th time it is called should print the number n.

I imagine that refs are necessary, but I do not know how to use them to make such a function.

afiori
  • 465
  • 3
  • 15

1 Answers1

0

I found a solution with an external local reference

local val mem = ref 0 in
fun f () = 
  let val _ = mem := !mem + 1 in print (Int.toString (!mem)) end
end

A solution to a slightly different problem would be to generate the function

fun iter_int n =
let val i = ref 0
in  fn () => 
  let val j = !i 
  in  i := !i + 1 ; j 
  end 
end
afiori
  • 465
  • 3
  • 15
  • Thanks, I found also a different solution that actually works better for me, but I think your comment helped me understand local :) – afiori Feb 10 '20 at 15:29
  • 1
    I believe your second solution is the more common one, and it's the only one that works if you want more than one generator. – molbdnilo Feb 10 '20 at 15:34