Applying Functions to Lists and Other Expressions

In an expression like f[{a,b,c}] you are giving a list as the argument to a function. Often you need instead to apply a function directly to the elements of a list, rather than to the list as a whole. You can do this in the Wolfram Language using (RefLink[Apply, paclet:ref/Apply]).

This makes each element of the list an argument of the function f:

Apply[f,{a,b,c}]

This gives (RefLink[Times, paclet:ref/Times])[a,b,c] which yields the product of the elements in the list:

Apply[Times,{a,b,c}]

Here is a definition of a function that works like the built-in function (RefLink[GeometricMean, paclet:ref/GeometricMean]), written using (RefLink[Apply, paclet:ref/Apply]):

geom[list_]:=Apply[Times,list]^(1/Length[list])

Applying functions to lists and other expressions.

What (RefLink[Apply, paclet:ref/Apply]) does in general is to replace the head of an expression with the function you specify. Here it replaces (RefLink[Plus, paclet:ref/Plus]) by (RefLink[List, paclet:ref/List]):

Apply[List,a+b+c]

Here is a matrix:

m={{a,b,c},{b,c,d}}

Using (RefLink[Apply, paclet:ref/Apply]) without an explicit level specification replaces the top-level list with f:

Apply[f,m]

This applies f only to parts of m at level 1:

Apply[f,m,{1}]

This applies f at levels 0 through 1:

Apply[f,m,{0,1}]