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:
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:
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
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 !:
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.
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):
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
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?
- nothing, always
- The value of the last evaluated expression
- 0
- It's a syntax error
What does the ! at the end of sort! signal?
- The function is unsafe
- The function mutates (some of) its arguments
- The function returns a Bool
- The function is a macro
Which is the compact form of a function that doubles its argument?
- def double(x): 2x
- double(x) = 2x
- fn double(x) => 2x
- double = x -> {2x}