I would like to create a function with an internal state, but I do not want to have to initialize this internal state outside of the function (I want to rely only on calls to this function and I do not want the function to return anything). I think the following code does what I mean:
function foo() if @isdefined state global state state += 1 else global state state = 1 # 1st call: initialize internal state end end
which gives the following expected output:
julia> foo() 1 julia> foo() 2 julia> foo() 3
However, I see drawbacks with this code, e.g., maybe working with global mutable variable is not the best way as it is computationally expensive. On the other hand, I cannot think of a way to achieve what I described without using global variables. Note that the state of the function would only be accessed by the function itself. Any thought / advice?