Search code examples
callbackfunction-pointersjuliafunction-handle

Function Handles in Julia


What is the standard way to define a callback function, or a function handle in Julia?

Suppose I define

function myFun(a, b, c, d)
 a - 3* b - c * d # The return value
end

My goal is to fix b = 1, c = 2, d = 3, and pass myFun as a function of a. Something like:

newFun2(x) = myFun(x, 1 ,2, 3)
myReceiver(myFun2)

Solution

  • According to the documentation, the objective function for NLOpt should be of the form:

    function f(x::Vector, grad::Vector):
        if length(grad) > 0:
            ...set grad to gradient, in-place...
        return ...value of f(x)...
    end
    

    Thus, the code would need to look something like:

    function myFun(a, b, c, d, grad)
        a - 3* b - c * d # The return value
    end
    
    newFun2(x, grad) = myFun(x, 1 , 2, 3, grad)
    

    myFun() would have to compute the values of the grad vector as well as returning the objective function value, if it was to work successfully with optimization algorithms that use the derivative information that myFun() is required to write to grad.