Passing 'global' functions

It is recommended to pass global variables to functions. What I wonder is whether it is good practice to pass functions as well. These functions can be declared in global scope or in outer (relative to an inner) scope. I have seen some code where functions are passed but this does not appear to be really necessary for the program to run correctly.

Functions declared in global scope are constants, equivalent to const global variables, so it is not necessary to pass them as function arguments for good performance.

(It doesn’t hurt to pass functions as arguments, on the other hand, and higher-order functions are fast in Julia.)

3 Likes

Just be careful to not use a non-constant global variable bound to a function, like

julia> f = sin

or

julia> g = x -> 2x

This is sometime source of confusion. f and g here are not constants and cause type instabilities.

7 Likes