Julia Language Functions as arguments


Example

Functions are objects in Julia. Like any other objects, they can be passed as arguments to other functions. Functions that accept functions are known as higher-order functions.

For instance, we can implement an equivalent of the standard library's foreach function by taking a function f as the first parameter.

function myforeach(f, xs)
    for x in xs
        f(x)
    end
end

We can test that this function indeed works as we expect:

julia> myforeach(println, ["a", "b", "c"])
a
b
c

By taking a function as the first parameter, instead of a later parameter, we can use Julia's do block syntax. The do block syntax is just a convenient way to pass an anonymous function as the first argument to a function.

julia> myforeach([1, 2, 3]) do x
           println(x^x)
       end
1
4
27

Our implementation of myforeach above is roughly equivalent to the built-in foreach function. Many other built-in higher order functions also exist.

Higher-order functions are quite powerful. Sometimes, when working with higher-order functions, the exact operations being performed become unimportant and programs can become quite abstract. Combinators are examples of systems of highly abstract higher-order functions.