Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Julia support static variables with function-scope

Tags:

static

julia

In C, one can declare static variables with local function scope (example).

Can something similar be done in Julia?

My use case is declaring sub-functions, but do not want Julia to have to reparse them every time the code executes. Declaring them outside of the function is ugly and gives them higher scope, which I want to avoid.

example:

function foo(x)
    static bar = t -> stuff with t

    ...
    bar(y)
    ...
end

While I could declare bar() outside of foo(), I would prefer bar to only be in the local namespace.

Thank you.

like image 484
Mageek Avatar asked Jul 02 '14 21:07

Mageek


2 Answers

You can create a new scope around the function, to hold the variable.

let
    global foo
    function bar(t)
        #stuff with t
    end
    y = 2
    function foo(x)
        #...
        bar(y)
        #...
    end
end

Then only foo(x) will be visible to the outside

like image 58
ivarne Avatar answered Sep 29 '22 01:09

ivarne


Based on @ivarne's answer.

let bar = t -> t^2
    global foo
    function foo(x)
        bar(x)
    end
end

But I don't think this is an ideal solution. IMHO it would be better to have a static keyword. The extra block is unwieldy. There is some discussion about this in Julia development:

https://github.com/JuliaLang/julia/issues/15056

https://github.com/JuliaLang/julia/issues/12627

like image 28
becko Avatar answered Sep 29 '22 01:09

becko