[next][previous][up][top][index]
search for:

making functions

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

o1 = sq

o1 : Function
i2 : sq 10

o2 = 100
i3 : sq(5+5)

o3 = 100

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

o4 = tm

o4 : Function
i5 : tm(5,7)

o5 = 35

Functions can be used without assigning them to variables.

i6 : (i -> i^2) 7

o6 = 49

Another way to make new functions is to compose two old ones with the operator @@.

i7 : sincos = sin @@ cos

o7 = sincos

o7 : Function
i8 : sincos 2.2

o8 = -0.555115

o8 : RR
i9 : sin(cos(2.2))

o9 = -0.555115

o9 : RR

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))

o10 = compose

o10 : Function
i11 : sincos = compose(sin,cos)

o11 = sincos

o11 : Function
i12 : cossin = compose(cos,sin)

o12 = cossin

o12 : Function
i13 : sincos 2.2

o13 = -0.555115

o13 : RR
i14 : cossin 2.2

o14 = 0.690587

o14 : RR

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.


[next][previous][up][top][index]
search for: