Functions

Next: , Previous: Type Variables, Index: Index

Procedural abstraction, or functions, is a vital part of many languages. Mesham is no exception and allows for the programmer to use functions. The mechanism for arguments to a function is pass by reference.

function return type function name [function arguments]
{
body
};

return [value];


The simplest one, return will return a value or variable from a function. The rule is, if the return type is an element type, then the value is returned, otherwise the reference is returned. The function arguments are a little more complex than you might think. In order to pass a variable to a function you need to use the keyword var for instance, the arguments to pass two integers would be [var a:Int, var b:Int]. However, if the type is anything more complex, then it needs to go into the function body - so it would look like [var a,var b] with the code a:array[Int,10]; and b:array[Char,20]; in the function body. If you wish to return an element type (or nothing) from a function then its simple - use the type or void for the return type. I.e. function void abc[] and function Int add[var a:Int, var b:Int]. However, returning anything more complex, such as an array you will need to use a type variable as the return type.

Examples

function void helloworld[]
{
print["hello world!\n"];
};

Hopefully the first example needs no explanation.

function Int subtract[var a:Int, var b:Int, var c:String]
{
c:="Called Function!";
return a - b;
};

In the example above, variable c is of type string, passed from the caller - this function will assign a string to it and (seeing its pass by reference) this will modify c's value. The function then returns the value resulting from integers a minus b.

typevar T::=array[Int,10] :: allocated[single[1]];
function T copyarray [var i:T]
{
var x:T;
x:=i;
return x;
}

In the last example, the function is designed to copy the contents of one array to another. The function will return a variable of type T and also expects an argument - variable i of type T. Inside the function variable x is declared to be of type T, the contents are copied by the assignment and then the variablex is returned.

Last Modified: August 2008