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)
Usage:
julia> myfactorial(10)
3628800
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]))
Set(Symbol[:comparison,:ref,:call])
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.