Functions

### 25.1.2 Functions

You have already seen functions defined with :=. For example, to define a function sumprod which takes two inputs and returns a list with the sum and the product of the inputs, you can enter:

sumprod(a,b):=[a+b,a*b]

Afterwards, use this new function.

sumprod(3,5)

| ⎡ ⎣ | 8,15 | ⎤ ⎦

You can define functions that are computed with a sequence of instructions by putting the instructions between braces, where each command ends with a semicolon. To use local variables, you can declare them with the local keyword, followed by the variable names. The value returned by the function will be indicated with the return keyword. For example, the above function sumprod could also be defined by:

sumprod(a,b):={ local s,p; s:=a+b; p:=a*b; return [s,p]; }

To avoid using braces, the proc and end keywords may be used like this:

sumprod:=proc(a,b) local s,p; s:=a+b; p:=a*b; return [s,p]; end

Yet another way to define a function is by using the function…endfunction construction. With this approach, the function name and parameters follow the function keyword. This is otherwise like the previous approach. The sumprod function could be defined by:

function sumprod(a,b) local s,p; s:=a+b; p:=a*b; return [s,p]; endfunction