Like matrices and strings, functions are stored as ordinary variables in the symbol table. Function's treatment as variables explains the somewhat peculiar syntax required to create and store a function.
> logsin = function ( x ) { return log (x) .* sin (x) } <user-function>
The above statement creates a function, and assigns it to the
variable logsin
. The function can then be used like:
> logsin ( 2 ) 0.63
Like variables, function can be copied, re-assigned, and destroyed.
> y = logsin <user-function> > y (2) 0.63 > > // Overwrite it with a matrix > logsin = rand (2,2); > > // Check that y is still a function > y (3) 0.155
If you try re-assigning a built-in function you will get a run-time error message. The built-in functions, those that are programmed in C, are a permanent part of the environment. So that users may always rely on their availability, they cannot be re-assigned, or copied.
Variables that represent user-functions can also be part of list objects. Sometimes it can be useful to group functions that serve a similar purpose, or perform different parts of a larger procedure.
list = << logsin = logsin >> logsin > list.logsin (2) 0.63 > list.expsin = function ( x ) { return exp (x) .* sin (x) } expsin logsin > list.expsin (2) 6.72