Apply

Apply

Apply[ func, expr ] replaces the outer operation of an expression with another function.

Usages

Apply[ func, expr ]

Apply[ func, expr ] takes the arguments of expr and gives them to func. For example, the list {2, 3} is List[2, 3], so Apply[ Plus, {2, 3} ] gives Plus[2, 3], which is 2+3. This is useful to turn a list into a sum or product, or to get the terms of an expression as a list.

Example in out
Turn a list into a sum. Apply[ Plus, {2, 3} ] 2+3
Turn a sum into a product. Apply[ Times, a+b+c ] a b c
Get the terms of a polynomial as a list. poly := 2x^2 + 3x + 6
r := Apply[List, poly]
r = {2x^2, 3x, 6}
Get the arguments of a power. Apply[ List, x^2 ] {x, 2}
Calculate the sum of the numbers in a list. Apply[ CalcPlus, {2, 3, 4} ] 9
Calculate the product of the numbers in a list. Apply[ CalcTimes, {2, 3, 4} ] 24
Details
  • The result is calculated where possible: Apply[ CalcPlus, {2, 3, 4} ] gives 9, not CalcPlus[2, 3, 4].
  • If func is an expression instead of a function name, its outer operation is used: Apply[ 2+3, {a, b} ] gives a+b.
  • Apply is often combined with Map: Map[ Apply, times, { {-3,1}, {6,1} } ] gives {-3*1, 6*1}.
Invalid input Result
Apply[ Plus ] Error: the number of arguments should be 2
Warning

expr must be an expression with arguments, such as a list, sum or function. A number or a single variable has no arguments, so the result is func without arguments: Apply[ List, 4 ] gives {}, and Apply[ Sqrt, CalcPlus[2, 3] ] gives Sqrt[] because CalcPlus[2, 3] is the number 5. To apply a function to a single value, use FuncApplication.

See also: Map, FuncApplication, RemoveFunction