Skip to content
Tutorials Center
My learning

Topics

Lesson 7 of 40 ยท Basics

Functions

Learn Julia functions: long and short form, multiple return values, optional and keyword arguments, anonymous functions, do blocks and the ! naming convention.

Functions are the main unit of code in Julia. Where other languages organize programs around classes, Julia organizes them around functions that work on data. Almost everything you call, from println to +, is a function, and the functions you write are just as fast as the built-in ones because Julia compiles each one for the types it actually receives.

This lesson covers everything you need to write everyday functions: the two ways to define them, returning several values, optional and keyword arguments, anonymous functions, do blocks, and the ! naming convention for functions that change their arguments. Julia is not installed on this site, so the Julia code is read-only. The runnable examples are Python stand-ins that show the same ideas, and each one says what is real Julia and what is a simulation.

Defining a function

The long form uses function ... end. The value of the last expression is returned automatically, so an explicit return is only needed for an early exit.

JULIA
function area(width, height)
    return width * height
end

function describe(n)
    n < 0 && return "negative"      # early exit
    n == 0 && return "zero"
    "positive"                      # last expression is returned
end

area(3, 4)        # 12
describe(-5)      # "negative"
describe(7)       # "positive"

For one-line functions, the short form reads like a math definition:

JULIA
square(x) = x^2
hypot2(a, b) = sqrt(a^2 + b^2)

square(9)         # 81
hypot2(3, 4)      # 5.0

Both forms create the same kind of object. Use the short form when the body is a single expression and the long form when you need several statements. Function names are lowercase by convention, with no underscores unless that helps readability (isempty, startswith, but parse_config if you must).

Ways to write a function

Long form function ... end for several statements.
Short form f(x) = x^2 for one expression.
Anonymous x -> x^2 with no name, passed to others.
1 / 2

Return values and tuples

A function returns exactly one value, but that value can be a tuple, and tuples can be unpacked on the left side of an assignment. This is how Julia gives you "multiple return values".

JULIA
function min_max(values)
    return minimum(values), maximum(values)   # a tuple
end

lo, hi = min_max([4, 9, 1, 7])
println(lo, " ", hi)       # 1 9

q, r = divrem(17, 5)       # built-in: quotient and remainder
println(q, " ", r)         # 3 2

If you only want one of the values, assign the other to _: q, _ = divrem(17, 5). A function that has nothing useful to return, like println, returns the special value nothing. You will meet tuples in depth in Tuples and Named Tuples.

You may also add a return type annotation: function ratio(a, b)::Float64. Julia converts the result to that type, or raises an error if it cannot. It is rarely needed for speed; use it when it documents intent.

Optional arguments

Give an argument a default value and callers may leave it out. Optional arguments must come after the required ones.

JULIA
function greet(name, greeting = "Hello")
    return "$greeting, $name!"
end

greet("Ada")            # "Hello, Ada!"
greet("Ada", "Hi")      # "Hi, Ada!"

Under the hood Julia simply defines two methods, greet(name) and greet(name, greeting), and the first one calls the second with the default filled in. That is why optional arguments take part in multiple dispatch. A default may even refer to earlier arguments: f(a, b = a * 2).

Keyword arguments

Keyword arguments are written after a semicolon in the definition and are given by name in the call. They make long argument lists readable and let callers skip the ones they do not care about.

JULIA
function draw_box(; width = 10, height = 5, border = '#')
    for row in 1:height
        line = row in (1, height) ? border^width : border * " "^(width - 2) * border
        println(line)
    end
end

draw_box()                          # all defaults
draw_box(width = 6, height = 3)     # override two
draw_box(height = 2, border = '*')  # order does not matter

A keyword without a default is required: function area(; width, height) raises an UndefKeywordError if either is missing. You can combine positional and keyword arguments, with the keywords after the semicolon: function plot_line(xs, ys; color = :blue). In a call, a comma works too (plot_line(xs, ys, color = :red)), but many people keep the semicolon as a visual separator.

Two details to remember. First, keyword arguments are matched by name, but they are not used to choose between methods. Dispatch looks only at the positional arguments. Second, if you already have a dictionary-like collection of options you can splat it: draw_box(; opts...).

Variable numbers of arguments

Three dots after the last parameter collect extra positional arguments into a tuple. The same three dots in a call spread a collection into separate arguments.

JULIA
function total(first, rest...)
    s = first
    for x in rest
        s += x
    end
    return s
end

total(1)                # 1
total(1, 2, 3, 4)       # 10

numbers = [5, 6, 7]
total(numbers...)       # same as total(5, 6, 7), gives 18
max(numbers...)         # 7

Anonymous functions and function values

Functions are ordinary values. You can store them in variables, put them in collections and pass them to other functions. An anonymous function has no name and is written with an arrow.

JULIA
square = x -> x^2
add = (a, b) -> a + b

map(x -> x^2, [1, 2, 3])            # [1, 4, 9]
filter(n -> n % 2 == 0, 1:10)       # [2, 4, 6, 8, 10]
sort(["pear", "fig", "banana"], by = length)   # ["fig", "pear", "banana"]

Existing functions work the same way as arguments: map(sqrt, [4, 9, 16]) gives [2.0, 3.0, 4.0]. Two operators combine functions: โˆ˜ (type \circ and press Tab) composes them, and |> pipes a value through them.

JULIA
shout = uppercase โˆ˜ strip
shout("  hello ")                 # "HELLO"

"  hello " |> strip |> uppercase  # "HELLO"

do blocks

When the last argument of a call is a function and that function is longer than one line, a do block reads far better than a long anonymous function inside parentheses. Julia puts the block's code in as the first argument.

JULIA
result = map([1, 2, 3]) do x
    y = x * 10
    y + 1
end
# result == [11, 21, 31]

open("notes.txt", "w") do io
    println(io, "first line")
    println(io, "second line")
end        # the file is closed automatically, even after an error

The second example is the typical real-world use: open(f, filename, mode) opens the file, calls your function with the open handle, and always closes it. You will see this pattern again in Files and I/O. If the callback takes more than one argument, list them after do: do a, b.

The ! convention

By convention, a function whose name ends in ! may modify one or more of its arguments, usually the first. The exclamation mark is only a signal to the reader; the language does not enforce it.

JULIA
v = [3, 1, 2]
sorted = sort(v)      # new array [1, 2, 3]; v is still [3, 1, 2]
sort!(v)              # v itself is now [1, 2, 3]
push!(v, 4)           # v is [1, 2, 3, 4]
empty!(v)             # v is []

Write your own mutating functions the same way and put the mutated argument first:

JULIA
function double!(xs)
    for i in eachindex(xs)
        xs[i] *= 2
    end
    return xs
end

Julia passes arguments by sharing: the function gets a reference to the same array, so changes to the contents are visible to the caller. Reassigning the parameter name (xs = [0]) only rebinds a local name and changes nothing outside.

Stand-ins you can run

Python also has defaults, keyword-only arguments, tuple returns and callbacks, so it is a good place to see the shapes of these ideas. Note the differences: Python keyword-only arguments come after a bare *, not a semicolon, and Python has no do block.

Python Defaults, keywords and multiple returns

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

A do block is just a function passed as the first argument. Python does not have the syntax, but a decorator or a plain function argument shows what Julia is doing for you, including the cleanup that open ... do guarantees. The second example also demonstrates the ! convention: Python's sorted makes a new list while list.sort changes the list in place.

Python Callbacks, cleanup and in-place functions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

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

    The value of the last evaluated expression is returned automatically. An explicit return is only needed for an early exit.
  2. 2. How do you define a keyword argument in a Julia function?

    Julia separates positional and keyword parameters with a semicolon. The bare star form is Python syntax.
  3. 3. What does the ! at the end of sort! mean?

    The exclamation mark warns the reader that an argument, usually the first, can be changed. The language does not enforce it.
  4. 4. What does a do block pass to the function it is attached to?

    The code in the block becomes an anonymous function placed first in the argument list, which is why it works with open, map and similar functions.

Summary

  • Define functions with function ... end or the short form f(x) = expr; the last expression is the return value.
  • Return several values as a tuple and unpack them with a, b = f().
  • Optional arguments follow the required ones; keyword arguments come after a semicolon and are given by name.
  • args... collects extra arguments and spreads a collection into a call.
  • Anonymous functions (x -> x^2) and do blocks let you pass behavior to other functions, including resource handlers like open.
  • A trailing ! signals that a function may change its argument.

Next: store many values in one place with Arrays and Vectors.