A long-form syntax is available for defining multi-line functions. This can be useful when we use imperative structures such as loops. The expression in tail position is returned. For instance, the below function uses a for
loop to compute the factorial of some integer n
:
function myfactorial(n)
fact = one(n)
for m in 1:n
fact *= m
end
fact
end
Usage:
julia> myfactorial(10)
3628800
In longer functions, it is common to see the return
statement used. The return
statement is not necessary in tail position, but it is still sometimes used for clarity. For instance, another way of writing the above function would be
function myfactorial(n)
fact = one(n)
for m in 1:n
fact *= m
end
return fact
end
which is identical in behaviour to the function above.