We should avoid global variables, such as, for example:
a = 2
function f(x)
return (x + a)^2
end
f(3)
As I understand, one way to pass data into a function is the use of anonymous functions. In this case,
we could do:
a = 2
function f(x,g)
return g(x)^2
end
f(3, x -> x+a)
Also I am not sure if this is equivalent in the function call:
g(x) = x + a
f(3,g)
First, as I understand, this second syntax results in faster code. If this is correct, I wander if this is equivalent:
a = 2
g(x) = x + a
function f(x)
return g(x)^2
end
f(3)
The variable a
, in this last example, is a global variable being used in g(x)
, so it seems that the problem of the first code is back.
Am I thinking this correctly? Is the anonymous function option effectively different in implementation and, thus, results faster code?
Or else we should always pass a
as an argument explicitly to f
, as in
a = 2
function f(x,a)
return (x + a)^2
end
f(3)
Thank you for your considerations.