Functions
Prerequisites: for loops and ranges
Functions package code you can reuse. There are two ways to define one:
function area(width, height)
return width * height
end
perimeter(w, h) = 2 * (w + h)
println(area(3, 4))
println(perimeter(3, 4))
12
14
- The
function ... endform is for longer functions. - The one-line assignment form
f(x) = ...is for short ones — it looks just like math. - A function returns the value of its last expression, so
returnis optional. Use it for clarity or to return early.
Default and keyword arguments
function greet(name, greeting = "Hello"; punctuation = "!", shout = false)
msg = "$greeting, $name$punctuation"
return shout ? uppercase(msg) : msg
end
println(greet("Ada"))
println(greet("Ada", "Hi"))
println(greet("Ada", punctuation = "?"))
println(greet("Ada"; shout = true))
Hello, Ada!
Hi, Ada!
Hello, Ada?
HELLO, ADA!
- Arguments with
= valueare optional. - Arguments after the
;are keyword arguments: callers pass them by name, in any order. Most options in Julia libraries are keyword arguments (likesort(xs, rev=true)).
Variable numbers of arguments
function total(xs...)
s = 0
for x in xs
s += x
end
return s
end
println(total())
println(total(1, 2, 3))
nums = [10, 20, 30]
println(total(nums...))
println(max(nums...))
0
6
60
30
xs... in a definition collects extra arguments into a tuple ("slurp");
nums... in a call spreads a collection into separate arguments
("splat").
Arguments are passed by sharing
function add_bonus!(scores)
for i in eachindex(scores)
scores[i] += 5
end
return scores
end
s = [70, 80]
add_bonus!(s)
println(s)
[75, 85]
A function receives the same array, not a copy, so it can modify it.
By convention, name such functions with a !. eachindex(a) gives the
valid indexes of a.
Practice
Write bmi(weight_kg, height_m) using the one-line form, and a
function describe_bmi(w, h; digits = 1) that returns a string like
BMI 22.9, rounding to digits decimals.
Show solution
bmi(weight_kg, height_m) = weight_kg / height_m^2
function describe_bmi(w, h; digits = 1)
return "BMI $(round(bmi(w, h), digits = digits))"
end
println(describe_bmi(70, 1.75))
println(describe_bmi(70, 1.75, digits = 3))
BMI 22.9
BMI 22.857