Algosim documentation: apply

apply

Applies a function to every element in a container.

Syntax

Description

If X is any container (including a set) and f a function, then apply(X, f) returns a copy of X in which each element x has been replaced by its image f(x) under f. For a set, this means that the cardinality of the result may be less than the cardinality of X unless f is injective.

If X is not a set, apply(X, f, n) will replace the elements at level n with their images under f, with level n = 1 being the top level (X itself).

The @ operator is mapped to the apply function. Hence, instead of apply(X, f) you typically write X @ f. This is particularly convenient when you need to apply several functions in succession: X @ f @ g ⋯.

Examples

sort(frequencies(compute(RandomInt(1000000)^2, n, 1, 1000000) @ digits @ first))
(1, 192164)
(2, 146925)
(3, 123873)
(4, 109158)
(5, 98564)
(6, 90439)
(7, 84566)
(8, 79092)
(9, 75219)
Alice ≔ ExampleData("Alice in Wonderland") \ 50
ALICE’S ADVENTURES IN WONDERLAND

Lewis Carroll
…
sort(frequencies(words(Alice) @ characters @ first @ UpperCase))
(A, 3358)
(B, 984)
(C, 903)
(D, 829)
(E, 378)
(F, 742)
(G, 574)
(H, 1575)
(I, 1968)
(J, 120)
(K, 262)
(L, 747)
(M, 897)
(N, 574)
(O, 1430)
(P, 493)
(Q, 186)
(R, 491)
(S, 2530)
(T, 4428)
(U, 262)
(V, 238)
(W, 1864)
(X, 3)
(Y, 550)
(Z, 2)
apply(SequenceList(4) @ IdentityMatrix, sin, 2)
(0.841470984808)

⎛0.841470984808               0⎞
⎝             0  0.841470984808⎠

⎛0.841470984808               0               0⎞
⎜             0  0.841470984808               0⎟
⎝             0               0  0.841470984808⎠

⎛0.841470984808               0               0               0⎞
⎜             0  0.841470984808               0               0⎟
⎜             0               0  0.841470984808               0⎟
⎝             0               0               0  0.841470984808⎠

See also