Julia, lesson 6
Functions give a name to a piece of logic so you can reuse it and reason about it on its own. They are also where Julia does its best work: code inside functions is compiled into fast machine code.
The full form uses function ... end:
For short functions there is a one-line form that looks like maths:
Both define the same thing. Call it with area(3, 4), which gives 12.
A function returns the value of its last expression, so area needs no special keyword. Use
return to leave early:
To return several values, separate them with commas. Julia packs them into a tuple, and the caller can unpack it straight into variables:
A parameter can have a default value, so callers may leave it out:
Keyword arguments come after a semicolon in the definition and are passed by name. They are perfect for options, because the call says what each value means:
2 exercises to try what you just read.
Variables created inside a function are local: they exist only during the call and never
clash with names outside. Inside a function, loops can update local variables freely, so the
global rule from the last lesson does not apply. That is why Julia programs usually put their
work in a function, often called main, and call it at the end of the file:
Functions receive their arguments by sharing: if you pass a list and the function changes
its contents, the caller sees the change. By convention, functions that modify an argument end
in !, like push! and sort!, which you will meet in the next lesson.
Write a function postage(weight; express=false) that returns the cost of sending a parcel:
express is true.Each input line holds a weight in kg, optionally followed by the word express. For each line,
print the cost.
Sample input:
Sample output:
Write a function clock(seconds) that returns three values: hours, minutes and seconds. Each
input line holds a whole number of seconds. For each line, print the time as H:MM:SS, with
minutes and seconds always written with two digits.
Use lpad(x, 2, '0') to pad a number to two digits: lpad(7, 2, '0') is "07".
Sample input:
Sample output:
function area(width, height)
width * height
endarea(width, height) = width * heightfunction safe_divide(a, b)
if b == 0
return nothing # `nothing` means "no value"
end
a / b
endfunction min_max(a, b)
a < b ? (a, b) : (b, a)
end
low, high = min_max(9, 4) # low = 4, high = 9greet(name, greeting="Hello") = println("$greeting, $name!")
greet("Ada") # Hello, Ada!
greet("Ada", "Hi") # Hi, Ada!function price(amount; tax=0.2, discount=0.0)
amount * (1 - discount) * (1 + tax)
end
price(100) # 120.0
price(100, discount=0.5) # 60.0function main()
total = 0
for line in readlines()
total += parse(Int, line) # no `global` needed here
end
println(total)
end
main()0.5
2.5 express
123
10
93725
591:02:05
0:00:59