Q&A: How use pure functions?

Question.  How do I use pure functions in Mathematica?

Answer. Sometimes we need a notation for a function that does not explicitly include any named variables and does not even itself have a name.  Instead of the named function

   square[x_] := x2

which may be used to square 5 as

   square[5]

we could use the pure function #^2& to square 5 by evaluating:

   #^2&[5]

 Itīs a good idea to enclose such a pure function in parentheses to avoid ambiguity in larger expressions:

   (#^2&)[5]

Hereīs an example that closely resembles the sort of thing you might need for animations, where the transformations you use depend upon some additional parameter (such as time or angle of rotation).  Start with the power function, which has two arguments:

   g[x_, n_] := xn

so tha g[3, 2] gives result 9.  Construct from g a function of one argument, its first, by fixing its second argument at, say, 2.  (Fixing one of the arguments to be some constant is what’s involved in the meaning of a partial derivative.)  And hereīs where the pure function comes in—do this without introducing a new named function:

   g[#, 2]&[3]

The preceding has result 9.  Of course, we could instead make a pure function that fixes the first argument of g.  For example:

   g[10, #]&[3]

The preceding has result 1000.--

[Home] [News] [Exams] [Files] [Homework] [Notes] [About] [Links]