Macaulay2 » Documentation
Packages » Macaulay2Doc > The Macaulay2 language > making functions
next | previous | forward | backward | up | index | toc

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 making a function for squaring numbers and calling it sq.
i1 : sq = i -> i^2

o1 = sq

o1 : FunctionClosure
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 : FunctionClosure
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 : FunctionClosure
i8 : sincos 2.2

o8 = -.5551149157594247

o8 : RR (of precision 53)
i9 : sin(cos(2.2))

o9 = -.5551149157594247

o9 : RR (of precision 53)
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 comp that will compose two functions, just as the operator @@ did above.
i10 : comp = (f,g) -> x -> f(g x)

o10 = comp

o10 : FunctionClosure
i11 : sincos = comp(sin,cos)

o11 = sincos

o11 : FunctionClosure
i12 : cossin = comp(cos,sin)

o12 = cossin

o12 : FunctionClosure
i13 : sincos 2.2

o13 = -.5551149157594247

o13 : RR (of precision 53)
i14 : cossin 2.2

o14 = .6905866885609112

o14 : RR (of precision 53)
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.