Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add FAQ with correct solution(s) for "static" variables in functions #20353

Open
dpsanders opened this issue Jan 31, 2017 · 6 comments
Open

Add FAQ with correct solution(s) for "static" variables in functions #20353

dpsanders opened this issue Jan 31, 2017 · 6 comments
Labels
domain:docs This change adds or pertains to documentation

Comments

@dpsanders
Copy link
Contributor

dpsanders commented Jan 31, 2017

cf. #15056, #12627

@dpsanders dpsanders changed the title Add FAQ with correct solution for "static" variables in functions Add FAQ with correct solution(s) for "static" variables in functions Jan 31, 2017
@cossio
Copy link
Contributor

cossio commented Jan 31, 2017

Agree this should be documented. But what is the correct solution?

@dpsanders
Copy link
Contributor Author

dpsanders commented Jan 31, 2017

One is to use a global closure inside a let as follows:

julia> let a = 0
           global function f()
               a += 1
           end
       end
f (generic function with 1 method)

julia> f()
1

julia> f()
2

julia> a
UndefVarError: a not defined

I am not sure how to make a const static variable like this, though.

@JeffBezanson
Copy link
Sponsor Member

I am not sure how to make a const static variable like this, though.

Don't change its value :)

@dpsanders
Copy link
Contributor Author

@ararslan ararslan added the domain:docs This change adds or pertains to documentation label Jan 31, 2017
@cossio
Copy link
Contributor

cossio commented Aug 12, 2018

What if the static variable depends on a type parameter of the function? In this case each specific method should get its own static variable. For example, suppose I want to write something like,

global function f(x::T) where {T <: Real}
  static a = zero(T)
  return a + 1
end

In this scenario the above approach of defining a using let outside the function body doesn't seem to work because then I don't have access to type parameter T.

@pranshumalik14
Copy link

pranshumalik14 commented Dec 16, 2020

Why can't the compiler or even lowered code in Julia do the let based allocation of the static variable per method definition of the generic function? I have no knowledge about how any of the compilation and transformation of Julia code works but it seems pretty possible to me. Is the static keyword being planned in the (near) future? Because it is also pretty useful for recursive functions.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
domain:docs This change adds or pertains to documentation
Projects
None yet
Development

No branches or pull requests

5 participants