module MyModule
    importall JuMP
    export @generate_nonnegative_variable
    
    macro generate_nonnegative_variable(m)
        v = gensym()
        v_expr = Expr(:call, esc(:>=), esc(v), 0) 
        return Expr(:macrocall, Symbol("@variable"), esc(m), v_expr)
    end
end
    
using JuMP
using MyModule
m = Model()

@generate_nonnegative_variable(m)
@generate_nonnegative_variable(m)
@generate_nonnegative_variable(m)

for i=1:5
    @generate_nonnegative_variable(m)
end

print(m)


I have the above code. The result looks like

Min 0

Subject to

 ##7322 ≥ 0

 ##7326 ≥ 0

 ##7328 ≥ 0

 ##7330 ≥ 0

 ##7330 ≥ 0

 ##7330 ≥ 0

 ##7330 ≥ 0

 ##7330 ≥ 0

While I was expecting all variables names are distinct, they are not. Those 
generated by the for-loop are all same. Why does this happen? What is a 
correct way of doing this?

I know that the above macro doesn't make any sense, since the JuMP package 
itself supports anonymous variable name, etc; but it's only part of things 
that I want to do. I think also there would be a better way to write the 
above macro, especially the Expr generation part... 

Reply via email to