Skip to content

Instantly share code, notes, and snippets.

@tk3369
Last active May 19, 2022 05:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tk3369/2220d1198126fb2c9d3473c464b23273 to your computer and use it in GitHub Desktop.
Save tk3369/2220d1198126fb2c9d3473c464b23273 to your computer and use it in GitHub Desktop.

Define a function such that it only executes its body once. The value from first execution is memoized at the module level.

module X

export once
let x = Ref{Any}()
    global function once(f::Function)
        isassigned(x) && return x[]
        x[] = f()
        return x[]
    end
end

end #module

REPL:

julia> using .X: once

julia> once() do
           println("cool")
           1
       end
cool
1

julia> once() do
           println("cool")
           1
       end
1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment