|
<< Click to Display Table of Contents >> Functions and procedures |
![]() ![]()
|
Note: If you are running one of the examples interactively in the Gekko input window, you should mark the code from function or procedure to the corresponding end, followed by [Enter]. Executing an function or procedure statements line by line in the Gekko input window will not work. |
It is possible for Gekko users to compose user-defined functions and procedures. This is described in depth on the help pages corresponding to FUNCTION and PROCEDURE. Note that user-defined functions and procedures do not live in Gekko databanks. Instead, it is advised to store them (as Gekko code) in external .gcm program files. Instead of using external .gcm files for functions/procedures, you may alternatively pack these into a .zip file and use this package file as a library (cf. the LIBRARY statement).
An example of a user-defined function that multiplies two values:
function val mul(val %x1, val %x2); |
An example of a corresponding procedure performing the same multiplication and printing it out.
procedure mul val %x1, val %x2; |
The TELL inside the procedure uses string interpolation, calculating the inside of the {}-curlies, and inserting the result into the resulting string.
A procedure is fundamentally the same as a user-defined function without return value. But procedures do not use parentheses or commas when called. This may pose challenges if you are inputting negative values in a procedure, like mul 3 -5;, expecting it to print out -15 as the result. In that case, Gekko will complain that it cannot find the procedure mul with only 1 argument, because it interprets mul 3 -5; as being the same as mul -2; , subtracting the two values. The solution to this could be to either use a function without return value instead (calling it with mul(3, -5);), enclosing the negative number in parentheses: mul 3 (-5);, or subtract it from 0: mul 3 0-5;
Another thing to note is that user-defined functions and procedures support a special variable type: name. On the inside of a function or procedure, a name type variable behaves just as a string, so the only difference between name and string is that, when called from the outside, a name argument does not need quotes, whereas a string argument does. For example:
procedure ratio name %n1, name %n2; |
If, instead, we had used string arguments, the procedure would have looked like this:
procedure ratio string %n1, string %n2; |
So nothing is changed in the inside of the function: the only difference is that the user now has to quote the arguments, which can be tedious for functions or procedures where some of the arguments are names of variables.
You may also use series type is argument in functions and procedures, but in many cases name type works better and provides equivalent syntax for calling the function/procedure.