TExcelTAD
Home › Julia › Julia map, filter & reduce

Julia map, filter & reduce

A higher-order function takes another function as an argument. Julia's Base includes a family of them that replace many hand-written loops with a single, expressive line: map, filter, reduce, foldl, mapreduce, any, all, count and friends.

map

map(f, collection) applies f to every element and collects the results:

julia · try it yourself
prices = [12.0, 7.5, 3.25]
with_tax = map(p -> round(p * 1.2, digits=2), prices)
println(with_tax)

println(map(uppercase, ["red", "green"]))
println(map(length, ["a", "abc", "ab"]))

# With several collections, f receives one element from each
println(map(+, [1, 2, 3], [10, 20, 30]))
println(map((name, n) -> "$name×$n", ["egg", "tomato"], [6, 3]))
[14.4, 9.0, 3.9]
["RED", "GREEN"]
[1, 3, 2]
[11, 22, 33]
["egg×6", "tomato×3"]

map! writes the results into an existing array, and foreach(f, xs) calls f only for its side effects (it returns nothing).

filter

filter(predicate, collection) keeps the elements for which the predicate returns true:

julia · try it yourself
nums = 1:20
println(filter(isodd, nums))
println(filter(n -> n % 7 == 0, nums))

words = ["level", "julia", "noon", "code"]
is_palindrome(w) = w == reverse(w)
println(filter(is_palindrome, words))

v = [3, -1, 4, -1, 5]
filter!(>(0), v)          # in-place version
println(v)
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
[7, 14]
["level", "noon"]
[3, 4, 5]

reduce and fold

reduce(op, collection) combines all elements with a binary operator: reduce(+, [a, b, c]) computes (a + b) + c. Provide init for an empty collection, or when the result type differs from the elements:

julia · try it yourself
println(reduce(+, [1, 2, 3, 4]))
println(reduce(*, 1:6))
println(reduce(max, [3, 9, 2]))
println(reduce(+, Int[]; init=0))

# foldl guarantees left-to-right order, which matters for non-associative ops
println(foldl(-, [10, 3, 2]))       # (10 - 3) - 2
println(foldr(-, [10, 3, 2]))       # 10 - (3 - 2)

# Building a string with init
println(foldl((acc, w) -> acc * w[1], ["portable", "network", "graphics"]; init=""))
10
720
9
0
5
9
png

Note: reduce doesn't promise an evaluation order, so use it only with associative operators like +, *, max. Use foldl/foldr when order matters.

mapreduce and friends

Many common reductions have dedicated functions, and most accept a function as the first argument to transform elements first, without building an intermediate array:

Function Meaning
sum(f, xs) sum of f(x)
prod(f, xs) product of f(x)
maximum(f, xs), minimum(f, xs) largest/smallest f(x)
count(pred, xs) how many satisfy pred
any(pred, xs), all(pred, xs) does any / every element satisfy pred
mapreduce(f, op, xs) reduce(op, map(f, xs)) without the temporary array
argmax(f, xs) the element where f is largest
julia · try it yourself
data = [3, -7, 2, 8, -1]
println(sum(abs, data))
println(sum(x -> x^2, data))
println(maximum(abs, data))
println(count(<(0), data))
println(any(iszero, data), " ", all(x -> abs(x) < 10, data))
println(mapreduce(x -> 2x, +, data))
println(argmax(abs, data))

words = ["kiwi", "banana", "fig"]
println(argmax(length, words))
21
127
8
2
false true
10
8
banana

A small pipeline

Higher-order functions combine naturally. Here we compute the total value of in-stock items:

julia · try it yourself
inventory = [
    (name="lamp", price=25.0, qty=4),
    (name="desk", price=150.0, qty=0),
    (name="chair", price=60.0, qty=6),
]
in_stock = filter(item -> item.qty > 0, inventory)
values = map(item -> item.price * item.qty, in_stock)
println(map(item -> item.name, in_stock))
println(values)
println(sum(values))
println(sum(item -> item.price * item.qty, inventory))
["lamp", "chair"]
[100.0, 360.0]
460.0
460.0

The last line computes the same total in one pass; items with qty = 0 contribute nothing.

Test yourself

What does filter(iseven, 1:6) return?

  1. [1, 3, 5]
  2. [2, 4, 6]
  3. 3
  4. [false, true, false, true, false, true]

What is foldl(-, [10, 3, 2])?

  1. 5
  2. 9
  3. -15
  4. 15

Which call counts the negative numbers in xs?

  1. sum(xs < 0)
  2. count(<(0), xs)
  3. length(xs, <0)
  4. filter(xs, <(0))