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:
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:
classify = function (n)
n < 0 && return "negative"
return n == 0 ? "zero" : "positive"
endSorting 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:
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:
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:
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:
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:
open("notes.txt", "w") do io
println(io, "first line")
println(io, "second line")
end # the file is closed automatically hereTest yourself
What does (a, b) -> a * b create?
- A tuple
- An anonymous function of two arguments
- A Pair
- A macro
In map(v) do x ... end, where does the do-block function go?
- It becomes the last argument
- It becomes the first argument of map
- It is called after map returns
- It replaces v
What is (sqrt ∘ abs)(-16)?
- 4.0
- -4.0
- an error
- 16