L-17 MCS 320 Friday 30 September 2005
| > | restart; |
1. Anonymous functions
Anonymous functions are often used in combination with the map command.
The command "map" applies an operation to a list. This operation is usually defined by a procedure, but since we are only are going to use this operation within the map, there is no need to give this operation a name, whence "anonymous" function.
| > | s := seq(x[i],i=0..10); |
Suppose we want to raise every element in the sequence s to the power 3:
| > | map(x->x^3,[s]); |
The "map" operator works on a list, we converted the sequence s to the list [s].
The function "x -> x^3" is an anonymous function.
Other uses of anonymous functions occur in the "select" and "remove" operations.
Suppose that from the sequence s, I would like to select all the variables with an even index.
| > | op(x[4]) mod 2; |
The above command illustrates how we select the index and test on parity.
| > | select(t->(op(t) mod 2 = 0),[s]); |
The first argument to select is an anonymous function which returns true or false.
Only those elements in the list ([s] in the example) for which the anonymous function returns true are selected. Notice that the name "t" is arbitrary. The operation remove is very similar to select, except that it removes those elements from the list for which the function returns true.
| > | remove(t -> (op(t) mod 2 = 1),[s]); |
The above command has removed all the variables with an odd index.
2. Composition of functions
We make new funcions by composition, using the @ operator.
| > | f := cos; # this is the cosine function, different from cos(x) |
| > | g := x -> x^2; |
| > | h := f@g; # h := x -> cos(x^2) |
We defined h as the result of the evaluation of f at (notice the @) the result of g.
| > | h(3.0); |
| > | h(z); |
Suppose we want to describe the motion of a projectile in time through space.
In space we follow a parabola: at time t=0, it is launched from ground level (height 0) and at time t =45, it hits the ground 120 miles further. Ignoring first the time, we know the spatial trajectory from the roots of the parabola:
| > | y := x -> x*(120-x); |
The y-function gives the height of the projectile at every x location, starting at the origin (at t=0), and ending 120 miles further.
We want to know the height of the projectile at every moment, in function of time.
| > | xt := t -> 120/45*t; |
The "xt" gives the function which describes the relation between time, going from 0 to 45 and space, for x varying between 0 (at time t=0) and 120 (at time 45).
| > | xt(0); xt(45); |
| > | h := y@xt; |
The composition of y with xt describes the height of a projectile moving at a constant speed, following a parabolic trajectory.
| > | h(34); h(34.0); h(z); |
| > |
The last evaluation gives us the expanded formula, which may lead again to expression swell.
With the @ we may build very quickly quite complicated functions, which are complicated when evaluated symbolically.