The idiom that seems to be used most commonly in Base is a closure around a variable hidden in a let scope. Note that your function must be declared global. See base/combinatorics.jl:L361-L380 <https://github.com/JuliaLang/julia/blob/f17ef9e66f71b641431ad111242728afdb8ae8c1/base/combinatorics.jl#L361-L380> for an example.
On Wednesday, February 4, 2015 at 9:49:33 AM UTC-5, Peter Simon wrote: > > Thanks, that looks like the ticket! I will try this out. > > On Tuesday, February 3, 2015 at 7:10:40 PM UTC-8, Erik Schnetter wrote: >> >> On Feb 3, 2015, at 20:30 , Erik Schnetter <[email protected]> wrote: >> > >> >> On Feb 3, 2015, at 20:22 , Peter Simon <[email protected]> wrote: >> >> >> >> Thanks, I will take a look at functors when I upgrade to 0.4. >> >> I didn't see this before. Here's another approach, without objects; it's >> functional and very Lispy. Probably also Julialy. >> >> Let's assume that there's an algorithm, and you have to pass a function >> f(x) to the algorithm. This function is expensive to evaluate, so you want >> to keep state around. In my field, this could be a residual evaluator that >> I need to pass to a solver >> >> First, define a function res(x, state) that takes the state as explicit >> argument. Here's an example: >> >> function res(x, state) >> y = state[1] >> state[1] = x >> return y >> end >> >> Then define your function f(x), together with the initial state: >> >> function myapplication >> mystate = [1] # just a list >> f(x) = res(x, mystate) # yes, f(x) is a local function >> ... solver(f) ... >> end >> >> Whenever f(x) is called, it remembers the state variable that you >> created. Since f(x) is a local function, it will go out of scope at some >> point. You can also create another function g(x) from res with a different >> state. >> >> Note that the state variable needs to be a reference type. I used a list >> here; you can also use an array, or a type that you declare yourself. >> However, it cannot be an immutable type. >> >> -erik >> >> -- >> Erik Schnetter <[email protected]> >> http://www.perimeterinstitute.ca/personal/eschnetter/ >> >> My email is as private as my paper mail. I therefore support encrypting >> and signing email messages. Get my PGP key from >> https://sks-keyservers.net. >> >>
