Global variables / performance / data passing

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?

That looks good to me (the second version since, like you point out, you don’t want to hardcode the function to optimize).

One small suggestion: It is common in Julia to put the function argument first, like this:

function minimize(computef, x)

That will enable the “do-block-syntax”; a convenient and readable way to create anonymous functions:

x, f = minimize(x) do y
    z = zero(y)
    for n = 1:data.a
      z += y * n
    end
    z
end