functions 8: Passing function as argument
It is possible in Julia to pass an function as argument, below we define a function called starline()
that prints a line of 50 stars:
starline() = println('*' ^ 50)
Output:
starline (generic function with 1 method)
Let’s test it:
starline()
Output:
**************************************************
Now let’s define a function called execute_function()
as follows:
function execute_function(a_function)
a_function()
end
Output:
execute_function (generic function with 1 method)
So how does this execute_function()
works. First we take in an argument as a_function
and in this statement a_function()
, we are treating it as a function and calling it. Now let’s test it:
execute_function(starline)
Output:
**************************************************
So it works. My hunch that Julia accepts a function and can call it is true. You can find notebook here https://gitlab.com/data-science-with-julia/code/-/blob/master/passing_function_as_arguments.ipynb