So, this code structure would be fine?:
struct Data
a :: Int64
end
const data = Data(4)
# Function that computes the function value
function computef(x :: Float64, data :: Data)
f = data.a * x^2
return f
end
# New function with different call, appropriate for "minimize" below
computef(x :: Float64) = computef(x,data)
# This the routine that requires a "computef(x)" function (dummy example)
function minimize(x)
fcurrent = computef(x)
y = x - 0.1
fnew = computef(y)
if ( fnew < fcurrent )
return y, fnew
else
return x, fcurrent
end
end
# Main program
x = 10.
println(" x = ",x," f = ",computef(x,data))
x, f = minimize(x)
println(" x = ",x," f = ",computef(x,data))
At the same time, I understand that most Julia functions would require the function “computef” as a parameter, and this structure would be more natural:
struct Data
a :: Int64
end
const data = Data(4)
# Function that computes the function value
function computef(x :: Float64, data :: Data)
f = data.a * x^2
return f
end
# This the routine that requires a "computef(x)" function (dummy example)
function minimize(x,computef)
fcurrent = computef(x)
y = x - 0.1
fnew = computef(y)
if ( fnew < fcurrent )
return y, fnew
else
return x, fcurrent
end
end
# Main program
x = 10.
println(" x = ",x," f = ", computef(x,data))
# Passing the function as an argument, as a closure
x, f = minimize(x, x -> computef(x,data) )
println(" x = ",x," f = ", computef(x,data))
Did I get things right? Is there any performance advice that should be added here?