First of all, apologies for the terrible title, but I’m having a hard time describing what I want to do.
I’ve written a lot of my code for an optimisation problem to look something like this:
using JuMP
# Function definitions
function get_variable_x(m::Model)
x = get(m.ext, :x, nothing)
return get_variable_x(m, x)
end
function get_variable_x(m::Model, x::Nothing)
return m.ext[:x] = @variable(m, x[i=1:10] >= 0)
end
get_variable_x(m::Model, x) = x
In essence, most of my functions first check if a Julia variable (in this case a JuMP optimisation variable) has been created before, returns it if so and creates it if not. The problem is that the function get_variable_x
is type unstable (I think I’m using that word correctly):
using Test
m = Model()
@inferred get_variable_x(m)
This produces the following error:
return type Array{VariableRef,1} does not match inferred return type Any
error(::String) at error.jl:33
top-level scope at test.jl:19
If I simply created the variable, this wouldn’t be a problem:
function get_variable_x_alt(m::Model)
return m.ext[:x] = @variable(m, x[i=1:10] >= 0)
end
m = Model()
@inferred get_variable_x_alt(m) # no error
Of course, I could further constrain the types that get_variable_x
can by writing this:
get_variable_x(m::Model, x::Array{VariableRef,1}) = x
However, I would like the Julia’s type inference to do the job for me. I’m sure that there is an elegant way of doing this, but I just can’t think of it.