Jump to content

User:LABoyd2/functions from manual 151008

From Wikibooks, open books for an open world

Calculating values

[edit | edit source]

Define a function for code readability and re-use.

Usage examples:

diameter = 20;
function r_from_dia(dia) = dia / 2;
echo("Diameter ", diameter, " is radius ", r_from_dia(diameter));

Functions can have multiple input variables of different types. The

Usage examples:

function f(x, vec) = x * vec[0] + 2 * x * vec[1];
echo(f(3, [4, 5])); // produces ECHO: 42

Default values

[edit | edit source]

Starting from the last parameter, it's possible to define default values. Those are assigned in case the function call does not give all the parameters.

Usage examples:

function f(p1, p2 = 3, p3 = 0) = 100 * p1 + 10 * p2 + p3;
echo(f(3, 2, 1)); // produces ECHO: 321
echo(f(3, 2));    // produces ECHO: 320
echo(f(3));       // produces ECHO: 330


Recursive function calls

[edit | edit source]

Recursive function calls are supported. Using the Conditional Operator "... ? ... : ... " it's possible to ensure the recursion is terminated.

Note: There is a built-in recursion limit to prevent the application to crash. If the limit is hit, the result of the function call is undef.

Usage examples:

// recursion - find the sum of the values in a vector (array)
// from the start (or s'th element) to the i'th element - remember elements are zero based

function sumv(v,i,s=0) = (i==s ? v[i] : v[i] + sumv(v,i-1,s));

vec=[ 10, 20, 30, 40 ];
echo("sum vec=", sumv(vec,2,1)); // is 20+30=50