Friday, November 5, 2010

M Language Tutorial - routines

Divide and conquer is the technique used to counter complexity from the beginning of software development history, A complex system in M language comprise of many files called routines.
label, quit and function
In general each line of code in a routine contains of one or no label following by a SPACE or TAB and then M command, other M code can make a call to any line of the routine that has a label at start of the file. Let create a file display.m in one of these paths specified in env. variable gtmroutines using any editor.
start
 write "display",!
 quit
other 
 write "other",!
nothing
 write "no",!
Now start gtm and try to make some call
$gtm
GTM>zlink "display"
GTM>do ^display
display
GTM>do start^display
display
GTM>do start+1^display
display
The name after ^ is name of routine same as filename without extension .m. Without any label, GTM will execute the code starting from line 1 of the routine. It does exactly the same with label start. Making a call to a line 1 from the label start mean start the execution from line 2 of the file. The execution terminate at command quit.
GTM>do start+3^display
other
no
GTM>do other^display  
other
no
GTM>do nothing^display
no
Calling a line 3 from label start is the same as calling label other. Because there is no quit command, GTM continues the execution at the end of file.
There is good practice always structure a routines as series of sections starting with a label and ending with a quit command. That way we can consider each label as a function name when making a call. Using offset from a label is considered a bad practice as it decrease readability of the code.
When calling a function within the same routine, we can remove the ^filename
talkto(who)
 do say("Hello",who); call a function in the same routine
 write "bla bla",!
 do say("Byte",who)
 quit

say(what,who)
 write what," ",who,!
 quit
GTM>zlink "stuff"

GTM>do talkto^stuff("John")
Hello John
bla bla
Byte John
calling function, passing parameters, return value
We pass parameters when calling M routine in parentheses separated by comma, the leading period . is used to indicate a parameter being passed as reference that is used to store the output of function.
$gtm
GTM>zedit "calc"
calc(a,b,ret)
 set ret=(2*a)+(3*b)
 quit
Now make a call
 
GTM>zlink "calc"
GTM>do ^calc(1,2,.result)
GTM>write result
8
M provides a facility called Extrinsic Variable to create a function that return value so it can be used in a expression
$gtm
GTM>zedit "calc"
calc(a,b,ret)
 set ret=(2*a)+(3*b)
 quit

othercalc(a,b)
 quit (2*a)+(3*b); the function must put return value  after quit command

GTM>zlink "calc"
GTM>write $$othercalc^calc(1,2); put $$ before the name of function when calling
8
GTM>set x=$$calc^calc(2,3)     
%GTM-E-QUITARGREQD, Quit from an extrinsic must have an argument

No comments: