using TidierIteration;
x = [3:6;];
f(x) = x^2;
apply(x, f)4-element Vector{Int64}:
9
16
25
36
The apply family consists of functions that help apply a function f to a collection x.
In base Julia there is already the map function, but
It does not work on dictionaries;
The function is the first argument, and the collection is the second. This make it less “pipeable”.
We will cover some common cases below.
Given a collection x and a one-variable function f, we can apply f to each element of x as follows:
This, of course, is the same as
or
Things get more interesting when we have a dictionary as follows:
while map(f, d) gives an error.
We can see a dictionary as a collection with named entries, and apply(d, f) means that we apply f to each value of d while keeping the keys of d intact.
In case you want to modify the keys of a dictionary, there is the special function
If you just want to apply f for its side-effects and return nothing, use
In case you want to convert each output of f to a specific type, you can always pass a compose function:
We can apply a two-variable function f to two collections x and y by applying f to each pair (x_i, y_i) where x_i is the i-th element of x and y_i the i-th element of y. If x and y have different sizes, we iterate until one of them ends.
When x and y are dictionaries, we iterate on the set of common keys:
In this case, we can use the index of each element of x as the first variable to be applied on f, that is, we apply f on the pairs (i, x_i) for each index i of x. It is important to note that i is the first argument to be passed to f.
4-element Vector{Dict{Int64, Int64}}:
Dict(1 => 3)
Dict(2 => 4)
Dict(3 => 5)
Dict(4 => 6)
When x is a dictionary, the elements i are the keys of x:
When the output of f is a dataframe, we can bind all rows (or columns) quickly as follows:
or
We can apply a p-variable function to a collection of p elements as follows: