TExcelTAD
Home › Julia › Julia Anonymous Functions & do-Blocks

Julia Anonymous Functions & do-Blocks

An anonymous function is a function without a name. It is perfect for short pieces of logic that you pass to another function, such as a sorting key or a filter condition.

The arrow syntax

x -> expression creates a function of one argument. Use parentheses for zero or several arguments:

julia · try it yourself
square = x -> x^2
add = (a, b) -> a + b
hello = () -> "hello!"

println(square(9))
println(add(2, 3))
println(hello())

println(map(x -> x * 10, [1, 2, 3]))
println(filter(w -> length(w) > 3, ["to", "be", "julia", "fast"]))
81
5
hello!
[10, 20, 30]
["julia", "fast"]

There is also a multi-line form:

julia
classify = function (n)
    n < 0 && return "negative"
    return n == 0 ? "zero" : "positive"
end

Sorting with a key

Many Base functions accept a function as a keyword argument. sort uses by to choose the sort key and rev to reverse:

julia · try it yourself
people = [("Mia", 34), ("Leo", 19), ("Ava", 27)]
println(sort(people, by = p -> p[2]))
println(sort(people, by = p -> p[1], rev = true))
println(sort(["banana", "Kiwi", "apple"], by = lowercase))
println(maximum(p -> p[2], people))
println(findfirst(p -> p[2] < 20, people))
[("Leo", 19), ("Ava", 27), ("Mia", 34)]
[("Mia", 34), ("Leo", 19), ("Ava", 27)]
["apple", "banana", "Kiwi"]
34
2

Closures

An anonymous function can capture variables from the surrounding scope. Such a function is called a closure. A function that returns a closure acts like a factory:

julia · try it yourself
function make_multiplier(factor)
    return x -> x * factor
end

double = make_multiplier(2)
triple = make_multiplier(3)
println(double(7), " ", triple(7))

function make_counter()
    count = 0
    return () -> (count += 1)
end
counter = make_counter()
counter(); counter()
println(counter())
14 21
3

Function composition and piping

∘ (typed \circ) composes functions: (f ∘ g)(x) is f(g(x)). The pipe operator |> passes a value into a function, which reads left to right:

julia · try it yourself
clean = strip ∘ lowercase
println(clean("  HELLO World  "))

result = [3, 1, 2] |> sort |> reverse
println(result)

1:10 |> collect |> (v -> filter(iseven, v)) |> sum |> println

# Partial application with Base.Fix2: (x -> x > 5)
gt5 = >(5)
println(filter(gt5, [3, 7, 5, 9]))
hello world
[3, 2, 1]
30
[7, 9]

Comparison operators called with one argument, such as >(5) or ==("a"), return a function — a short way to write common predicates.

do-blocks

When a function's first argument is a function, Julia lets you write that argument as a do block after the call. This keeps long anonymous functions readable:

julia · try it yourself
squares = map([1, 2, 3, 4]) do x
    y = x^2
    isodd(x) ? -y : y
end
println(squares)

foreach(["a", "bb", "ccc"]) do s
    println(s, " has length ", length(s))
end

pairs_sum = map([1, 2], [10, 20]) do a, b
    a + b
end
println(pairs_sum)
[-1, 4, -9, 16]
a has length 1
bb has length 2
ccc has length 3
[11, 22]

map(xs) do x ... end is exactly map(x -> ..., xs). The best-known use is file handling, where the do block guarantees the file is closed even if an error occurs:

julia
open("notes.txt", "w") do io
    println(io, "first line")
    println(io, "second line")
end   # the file is closed automatically here

Test yourself

What does (a, b) -> a * b create?

  1. A tuple
  2. An anonymous function of two arguments
  3. A Pair
  4. A macro

In map(v) do x ... end, where does the do-block function go?

  1. It becomes the last argument
  2. It becomes the first argument of map
  3. It is called after map returns
  4. It replaces v

What is (sqrt ∘ abs)(-16)?

  1. 4.0
  2. -4.0
  3. an error
  4. 16