Julia Language Recursive functions


Simple recursion

Using recursion and the ternary conditional operator, we can create an alternative implementation of the built-in factorial function:

myfactorial(n) = n == 0 ? 1 : n * myfactorial(n - 1)


julia> myfactorial(10)

Working with trees

Recursive functions are often most useful on data structures, especially tree data structures. Since expressions in Julia are tree structures, recursion can be quite useful for metaprogramming. For instance, the below function gathers a set of all heads used in an expression.

heads(ex::Expr) = reduce(∪, Set((ex.head,)), (heads(a) for a in ex.args))
heads(::Any) = Set{Symbol}()

We can check that our function is working as intended:

julia> heads(:(7 + 4x > 1 > A[0]))

This function is compact and uses a variety of more advanced techniques, such as the reduce higher order function, the Set data type, and generator expressions.