function input_arguments -> output_arguments statement statement statement ... endThe first line of a function definition is called the header, which starts with keyword function, followed by input arguments and output arguments, which are joined by an arrow ->. The header must end with a newline, and no other statements can appear in the line of the header after the output argument. The last line of the function must be the keyword end. Between the header and the last line is a sequence of statements.
In the function header, input_arguments and output_arguments are either a single variable name such as x, or a list of variable names, such as (x, y, z), or an empty list. Therefore a function header may look like one of the following
function x -> y // one input, one output function (x, y) -> z // two inputs, one output function (x, y, z) -> w // three inputs, one output function x -> (y, z) // one input, two outputs function x -> () // one input, no output function () -> z // no input, one output function () -> () // no input, no outputIn Shang, anything is also the list containing itself. Therefor x = (x), so it's ok to write function x -> y as function (x) -> (y)
Note that a variable name in the argument list may optionally contain the default argument value (See 6.11), and the domain (See 6.12) of values of the argument. Therefore, a function header may look like this
function (x = 0, y = 1) -> z // input arguments have default values function (x in _R, y _in _R) -> z // input arguments have domainsFor now, we will focus on the simplest case - an argument declaration only contains the argument name.
A function definition will evaluate to a value of type function. It doesn't automatically have a name. To be able to call the function later, usually we should assign the function definition to a variable, such as
>> sumto = function n -> s s = 0; for k = 1 : n s += k; end endThe above defines a function which takes a single argument n and calculates the sum of 1, 2, ..., n. The function is assigned to the variable sumto. Now we can call the function by using name sumto
>> sumto(100) 5050
oz 2009-12-22