The operator -> is used to make new functions. On its left we provide the names of the parameters to the function, and to the right we provide the body of the function, an expression involving those parameters whose value is to be computed when the function is applied. Let's illustrate this by makint a function for squaring numbers and calling it sq.
i1 : sq = i -> i^2 |
i2 : sq 10 |
i3 : sq(5+5) |
When the function is evaluated, the argument is evaluated and assigned temporarily as the value of the parameter i. In the example above, i was assigned the value 10, and then the body of the function was evaluated, yielding 100.
Here is how we make a function with more than one argument.
i4 : tm = (i,j) -> i*j |
i5 : tm(5,7) |
Functions can be used without assigning them to variables.
i6 : (i -> i^2) 7 |
Another way to make new functions is to compose two old ones with the operator @@.
i7 : sincos = sin @@ cos |
i8 : sincos 2.2 |
i9 : sin(cos(2.2)) |
Code that implements composition of functions is easy to write, because functions can create new functions and return them. We illustrate this by writing a function called compose that will compose two functions, just as the operator @@ did above.
i10 : compose = (f,g) -> x -> f(g(x)) |
i11 : sincos = compose(sin,cos) |
i12 : cossin = compose(cos,sin) |
i13 : sincos 2.2 |
i14 : cossin 2.2 |
We created two composite functions in the example above to illustrate an important point. The parameters f and g acquire values when sincos is created, and they acquire different values when cossin is created. These two sets of values do not interfere with each other, and the memory they occupy will be retained as long as they are needed. Indeed, the body of both functions is x -> f(g(x)), and the only difference between them is the values assigned to the parameters f and g.
The class of all functions is Function.