Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to correctly define and use global variables in the module in Julia?

Tags:

julia

In Fortran, we know that we can in a module define a global variable (use the private property), so that we can use the subroutines in the module to set or change the values of that variable. See below,

module Mod
integer, parameter :: r8=selected_real_kind(15,9)
real(kind=r8), private, save :: var
contains
subroutine f(x)
real(kind=r8) :: x
var = 2.0_r8*x
end subroutine f
end

As we can see, we can call f(x) and set the var in the module to be 2x.

Now in Julia, it seems like below,

module Mod
global var
function f(x::Float64)
global var = 2.0*x
return nothing
end
  1. I mean, in the function, if var is on the left hand side, do I have to specify the key word 'global' every time?

  2. I also tried to give the global var a type, like

    global var::Float64

But it gives me an error

syntax: type declarations on global variables are not yet supported

It seems i can only do either just specify nothing, like just

global var

or give it a value while setting its type,

global var=0.0::Float64

Is there better to just give the global var a type before using it?

like image 774
CRquantum Avatar asked Oct 28 '25 04:10

CRquantum


1 Answers

This is a way to make what you want and to make it efficient:

julia> const x = Ref(0)
Base.RefValue{Int64}(0)

julia> function f(y)
           x[] = y
       end

f (generic function with 1 method)

julia> x[]
0

julia> f(10)
10

julia> x[]
10

julia> f("10")
ERROR: MethodError: Cannot `convert` an object of type String to an object of type Int64

julia> f(5.0)
5.0

julia> x[]
5

Comments:

  1. I make x a const which makes sure that the compiler will know its type (so that it can optimize code)
  2. I make x a Ref to allow mutability of its contents and to make it clear later in the x[] = y statement that x[] part refers to a global variable (as variable x is not defined in a local scope of f)
  3. As you can see in the example I could not use "10" in the call of f as it does not have a matching type. Note though that I could use 5.0 (a float) as it can be converted to an integer.
like image 122
Bogumił Kamiński Avatar answered Oct 30 '25 15:10

Bogumił Kamiński