Doug Richardson
Doug Richardson

Reputation: 10811

How does type inference differ between constant and non-constant global variables?

From the Julia docs on array comprehensions:

The following example computes a weighted average of the current element and its left and right neighbor along a 1-d grid. :

julia> const x = rand(8)
8-element Array{Float64,1}:
 0.843025
 0.869052
 0.365105
 0.699456
 0.977653
 0.994953
 0.41084
 0.809411

julia> [ 0.25*x[i-1] + 0.5*x[i] + 0.25*x[i+1] for i=2:length(x)-1 ]
6-element Array{Float64,1}:
 0.736559
 0.57468
 0.685417
 0.912429
 0.8446
 0.656511

Note

In the above example, x is declared as constant because type inference in Julia does not work as well on non-constant global variables.

The resulting array type is inferred from the expression; in order to control the type explicitly, the type can be prepended to the comprehension. For example, in the above example we could have avoided declaring x as constant, and ensured that the result is of type Float64 by writing:

Float64[ 0.25*x[i-1] + 0.5*x[i] + 0.25*x[i+1] for i=2:length(x)-1 ]

What does the note near the end mean? That is, how does type inference differ between constant and non-constant global variables?

Upvotes: 1

Views: 165

Answers (1)

Daniel Arndt
Daniel Arndt

Reputation: 2543

I believe the problem is that if x is not declared as a const, then Julia has no idea if the type of that variable will ever change (because it never falls out of scope as a global). For this reason, Julia would need to assume x is of type Any.

If x is declared as a const, however, Julia can safely assume that its type will not change, and Julia can make optimizations based on that information.

Note that if you do not declare x as a const, then the returned type from the list comprehension will be Array{Any,1}

Upvotes: 6

Related Questions