TExcelTAD
Home › Julia › Julia Functions

Julia Functions

A function maps argument values to a return value. Functions are the core building block of Julia programs — and the unit the compiler optimises — so most code should live inside them.

Defining functions

There are two forms. The full form uses function ... end; the compact assignment form fits on one line:

julia · try it yourself
function area(width, height)
    return width * height
end

perimeter(width, height) = 2 * (width + height)

println(area(3, 4))
println(perimeter(3, 4))
println(area(2.5, 2))
12
14
5.0

Return values

A function returns the value of the last expression evaluated, so return is optional on the last line. Use return to leave early. To return several values, return a tuple and destructure it:

julia · try it yourself
function stats(values)
    isempty(values) && return nothing
    lo, hi = extrema(values)
    avg = sum(values) / length(values)
    lo, hi, avg          # last expression = return value (a tuple)
end

low, high, mean_value = stats([4, 8, 15, 16, 23, 42])
println(low, " ", high, " ", mean_value)
println(stats(Int[]))
4 42 18.0
nothing

A function that only has side effects (printing, mutating) conventionally returns nothing.

Default (optional) arguments

julia · try it yourself
function greet(name, greeting="Hello", punctuation="!")
    return "$greeting, $name$punctuation"
end

println(greet("Sam"))
println(greet("Sam", "Hi"))
println(greet("Sam", "Good morning", "."))
Hello, Sam!
Hi, Sam!
Good morning, Sam.

Default values may refer to earlier arguments: f(x, y=2x) = x + y.

Argument passing: "pass by sharing"

Arguments are not copied. A function receives the same object the caller passed, so mutating a mutable argument (an array, a dictionary) is visible outside. Rebinding the argument name, however, only affects the local name. By convention, functions that mutate an argument have names ending in !:

julia · try it yourself
function add_bonus!(scores, bonus)
    for i in eachindex(scores)
        scores[i] += bonus
    end
    return scores
end

function try_to_replace(scores)
    scores = [0, 0, 0]       # rebinds the local name only
    return scores
end

s = [70, 85, 90]
add_bonus!(s, 5)
println(s)
try_to_replace(s)
println(s)
[75, 90, 95]
[75, 90, 95]

Functions are values

Functions are first-class objects: you can store them in variables, pass them to other functions and return them.

julia · try it yourself
apply_twice(f, x) = f(f(x))
inc(x) = x + 1

println(apply_twice(inc, 10))
println(apply_twice(sqrt, 16))

ops = [+, -, *]
for op in ops
    println(op, "(6, 3) = ", op(6, 3))
end

f = uppercase
println(f("julia"))
12
2.0
+(6, 3) = 9
-(6, 3) = 3
*(6, 3) = 18
JULIA

Operators like + are ordinary functions: 1 + 2 is just nicer syntax for +(1, 2).

Type annotations on arguments

Arguments can be annotated with ::Type. This restricts which values the function accepts and, more importantly, lets you define different methods for different types (see Methods & Multiple Dispatch):

julia · try it yourself
describe(x::Integer) = "the integer $x"
describe(x::AbstractString) = "the text \"$x\""
describe(x) = "something else: $x"

println(describe(42))
println(describe("hi"))
println(describe(3.5))
the integer 42
the text "hi"
something else: 3.5

Recursion

julia · try it yourself
fib(n) = n <= 2 ? 1 : fib(n - 1) + fib(n - 2)
println([fib(n) for n in 1:10])

function power_set_size(n::Int)
    n == 0 && return 1
    return 2 * power_set_size(n - 1)
end
println(power_set_size(10))
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
1024

Test yourself

What does a Julia function return if it has no return statement?

  1. nothing, always
  2. The value of the last evaluated expression
  3. 0
  4. It's a syntax error

What does the ! at the end of sort! signal?

  1. The function is unsafe
  2. The function mutates (some of) its arguments
  3. The function returns a Bool
  4. The function is a macro

Which is the compact form of a function that doubles its argument?

  1. def double(x): 2x
  2. double(x) = 2x
  3. fn double(x) => 2x
  4. double = x -> {2x}