Passing a function as an objective function in JuMP

There is nothing stopping you from going

julia> using JuMP

julia> m=Model()
Feasibility problem with:
 * 0 linear constraints
 * 0 variables
Solver is default solver

julia> @variable(m, x)
x

julia> function foo(x)
       2x + 1
       end
foo (generic function with 1 method)

julia> @objective(m, Min, foo(x))
2 x + 1

julia> JuMP.getobjective(m)
2 x + 1

But, if you are building an objective with a large number of elements, this is going to be slow.

Is it really too much to use the macro? With a good data-structure and intendation, it is normally pretty easy to read. Alternatively, you could break it up into a few @expression objects…

julia> using JuMP

julia> m=Model()
Feasibility problem with:
 * 0 linear constraints
 * 0 variables
Solver is default solver

julia> @variable(m, x)
x

julia> @expression(m, foo, 2x + 1)
2 x + 1

julia> @objective(m, Min, foo)
2 x + 1

julia> JuMP.getobjective(m)
2 x + 1
2 Likes