Learn/Julia/6. Functions
Lesson 6 of 8
Sign in

Julia, lesson 6

Functions

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.

Two ways to define a function

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.

Return values

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:

Default and keyword arguments

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.

Exercise 1

Parcel postage

Press Ctrl Enter or Check to test your code.

Exercise 2

Stopwatch display

Press Ctrl Enter or Check to test your code.

Scope

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.

Further reading

  • Julia manual: Functions
  • Julia manual: Scope of variables

Write a function postage(weight; express=false) that returns the cost of sending a parcel:

  • 3 for parcels up to 1 kg (inclusive),
  • 5 for parcels up to 5 kg,
  • 9 for heavier parcels,
  • and double the price when 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
end
area(width, height) = width * height
function safe_divide(a, b)
    if b == 0
        return nothing     # `nothing` means "no value"
    end
    a / b
end
function min_max(a, b)
    a < b ? (a, b) : (b, a)
end

low, high = min_max(9, 4)   # low = 4, high = 9
greet(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.0
function 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
12
3
10
9
3725
59
1:02:05
0:00:59