### 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))

| ⎡ ⎣ | 4,3,2,1 | ⎤ ⎦

apply(x->x^2,[3,5,1])

or:

map([3,5,1],x->x^2)

(or first define the function h(x)=x2.)

h(x):=x^2

then:

apply(h,[3,5,1])

or:

map([3,5,1],h)

| ⎡ ⎣ | 9,25,1 | ⎤ ⎦

Define the function g(x)=[x,x2,x3].

g:=(x)->[x,x^2,x^3]

then:

apply(g,[3,5,1])

or:

map([3,5,1],g)

⎡
⎢
⎢
⎣

3 | 9 | 27
5 | 25 | 125
1 | 1 | 1

⎤
⎥
⎥
⎦

##### 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]).