afiori
afiori

Reputation: 639

Simple function with internal state

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.

Upvotes: 0

Views: 24

Answers (1)

afiori
afiori

Reputation: 639

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

Upvotes: 0

Related Questions