6.3.28 Applying a function of one variable to the elements of a list
The apply and
map commands can both apply a
function to a list of elements, but take arguments in different orders
(that is required for compatibility reasons).
The apply command also works on matrices (see
Section 14.2.6) and the map command also works on
polynomials in internal sparse format (see Section 11.1.3).
-
apply takes two arguments:
-
f, a function.
- L, a list.
- apply(f,L) returns a list whose elements are f(x)
for the elements x of L.
Note that apply returns a list ([]) even if the
second argument is not a list.
-
map takes two arguments:
-
L, a list or a polynomial in internal format (see
Section 11.1.2).
- f, a function.
- map(L,f) returns a list whose elements are f(x)
for the elements x of L.
Examples
apply(x->sqrt(x),[16,9,4,1]) |
or:
map([16,9,4,1],x->sqrt(x)) |
or:
(or first define the function h(x)=x2.)
then:
or:
Define the function g(x)=[x,x2,x3].
then:
or:
Remark.
If x is not a symbol, then it needs to be purged.
Note that if L1, L2 and L3 are lists, then
sizes([L1,L2,L3]) is equivalent to
map(size,[L1,L2,L3]).