🎓 A1Learner
🔍
0 of 52 lessons completed

Julia Array Functions

Array functions read, reorder, and transform the values of an array. Most of them return a result and leave the original array alone.

Summary functions read the whole array

One array feeds five different functions. Each print shows a single fact about it.

a = [4, 1, 7]
println(sum(a))
println(maximum(a))
println(minimum(a))
println(first(a))
println(last(a))

sort copies while sort! changes in place

sort returns a sorted copy and the original keeps its order. sort! then sorts the original itself, and reverse flips a copy of it.

a = [3, 1, 2]
println(sort(a))
println(a)
sort!(a)
println(a)
println(reverse(a))

map transforms and filter selects

map applies the anonymous function to every value. filter keeps only the values where the test is true.

a = [1, 2, 3, 4]
println(map(x -> x * 10, a))
println(filter(x -> x > 2, a))

Example

prices = [8, 3, 5]
println(sort(prices))
println(sum(prices))
println(map(x -> x + 1, prices))
println(filter(x -> x > 4, prices))

Key points

  • sum: sum(a) adds all the values in a.
  • maximum and minimum: maximum(a) gives the largest value and minimum(a) gives the smallest.
  • first and last: first(a) gives the first value and last(a) gives the last value.
  • sort: sort(a) returns a new sorted array and leaves a unchanged.
  • sort!: sort!(a) sorts a itself, in place.
  • reverse: reverse(a) returns a new array with the values in reverse order.
  • map and filter: map applies a function to each value, and filter keeps only the values that pass a test.

In this example, sort returns the prices in order as [3, 5, 8] while prices itself stays unchanged. sum adds the prices to 16, map adds 1 to each price in the original order, and filter keeps the two prices above 4.

Try it Yourself

Edit the code, then press Run.

Running is simulated · JuliaHub

Exercise

You call sort(a) and then print a. What do you see?