Previous Up Next

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

Note that apply returns a list ([]) even if the second argument is not a list.

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)
     



3927
525125
111



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


Previous Up Next