10  Functional Programming

using StatsBase

10.1 Apply function elementwise: map()

a = collect(1:5)
5-element Vector{Int64}:
 1
 2
 3
 4
 5
map(x -> x^2, a)
5-element Vector{Int64}:
  1
  4
  9
 16
 25

10.2 Apply function on array slices: mapslices()

A = reshape(collect(2:2:24), 3, 4)
3×4 Matrix{Int64}:
 2   8  14  20
 4  10  16  22
 6  12  18  24

With the dims, you choose which dimensions to collapse. (This is the opposite from R’s apply(), where you choose which dimensions to keep)



Get mean value of each column:

mapslices(mean, A, dims = 1)
1×4 Matrix{Float64}:
 4.0  10.0  16.0  22.0

Get mean value of each row:

mapslices(mean, A, dims = 2)
3×1 Matrix{Float64}:
 11.0
 13.0
 15.0

10.3 Filter

v = collect(1:20);
filter(x -> x > 10, v)
10-element Vector{Int64}:
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20

10.4 Reduce

v = collect(2:5)
reduce(*, v)
120

same as

prod(v)
120