In this tutorial we are going to look at functions and how to build your own.
Using Functions
Functions are just like functions in real life. They are a named operation that takes a number or arguments ( parameters ) and returns a value.
Program( ) Number y; Begin y := Sin(30); Output y; End;
For normal people angles are measured in degrees - so GraRLS uses degrees rather than radians, mathematician can write their own wrapper functions to use radians.
Defining your own functions is similar to defining a Shape except we need a way or returning the result.
Function return_type function_name ( parameters ) local variables Begin some code End;
the code section must contain at least one statement of the form :-
Return expression;
The expression must yield a result of the type specified for the function.
A function never draws anything and so does not have a graphics context.
Program( ) Number y; Begin y := Squared(5); Output y; End; Function Number Squared(Number x) Begin Return x * x; End;
Reference Parameters
With the simple example above the value passed to the function as 'x' will not affect the value passed.
Program( ) Number x, y; Begin x := 5; y := Squared(x); Output x, y; End; Function Number Squared(Number x) Begin x := x * x; Return x; End;
Here the value 'x' inside the function it totally independent of the 'x' ( even though it has the same name ) in the main program so after the call to the function the value of 'x' in the main program is still 5.
If however the function had been defined as :-
Function Number Squared(Ref Number x) Begin x := x * x; Return x; End;
Then callers value would have chaged - even it it has a different name.
Program( ) Number a, y; Begin a := 5; y := Squared(a); Output a, y; End;
In this case the value of 'a' is changed. The 'Ref' ( reference ) keyword tells the system that 'x' is not an independent local variable but is a reference to a variable in the calling routine.
This mechanism has two aims. The first it to allow a function to return more than a single value. The second is for efficency - if the value is some large compound type creating a local copy could use a lot of memory and take a lot of time. In this case is we do do not intend to actually change the value we would flag the parameter as constant.
Function Number Squared(Const Ref Number x) Begin Return x * x; End;
The constant attribute will tell the compiler to report an error if the function does try to modify the value. You can also flag non-reference parameters as Const. This will simply act as a check that you have not done something silly. The above example is rather silly but illustrates the point. In more complex programs the mechanism is genuinely useful.