In Julia, how to create a function that saves its own internal state?

Or a functor?

struct F
  state
end
(o::F)(x) = o.state + x

f = F(1)

f(2)
3


more specifically:

julia> Base.@kwdef mutable struct F
         state = nothing
       end
F

julia> function (o::F)()
         if o.state == nothing
           o.state = 1
         else
           o.state += 1
         end
       end

julia> f = F()
F(nothing)

julia> f()
1

julia> f()
2

julia> f()
3

julia> f.state # now this is part of the language, because f is an instance of F
3

17 Likes