Monday, November 15, 2010

M Language Tutorial - if, else and boolean condition

M language has no concept of structure that are familiar in other programming languages. In M all are commands including if,else,for.
if and else commands
GTM>set x=1

GTM>if x=1 write "boom"; if condition is satisfied
boom
GTM>if x=2 write "bang";  if condition is not satisfied
The if command support AND , OR, NOT condition
GTM>set x=1,y=2

GTM>if x=1,y=1 write "bang" ; we use , to denote AND

GTM>if x=1,y=2 write "bang"
bang

GTM> if (x=1)&(y=2) write "bang"; other way to express AND is to use &
bang

GTM>if x=1!y=1 write "boom"; we use ! to denote OR 
boom
GTM>if 1=0 write "oh" 

GTM>if '1=0 write "oh"; we use '  to denote a negation
oh
Internally, if set a special value $TEST to 1 (TRUE) or 0 (FALSE) depending on whether the condition is satisfied or not. $TEST is set to 1 at the start of gtm. The if command without condition will use $TEST as condition.
$gtm
GTM>write $TEST
1
GTM>if 1=0

GTM>write $TEST
0
GTM>if  write "hello"! note two SPACEs after if

GTM>if $TEST=1 write "hello"! equivalent to above

GTM>if 1=1

GTM>write $TEST
1
GTM>if  write "hello"; note two SPACEs after if
hello
GTM>if $TEST=1 write "hello"; equivalent to above
hello
else is command that perform the command followed it if the $TEST variable is 0
GTM>set x=1

GTM>if x>1 write "world"

GTM>else  write "moon"; note two SPACES after else
moon
GTM>if $TEST=0  write "moon"; equivalent to above
moon
command's postcondition
execution of almost all commands can be controlled by following it with a colon and a truthvalue expression.
GTM>set n=1
GTM>write:n>0 "hello"
hello
GTM>write:n>1 "world"
GTM> 

block of multi line of codes under if,else
M support execute multi line of code under if,else, for in the routine
GTM>zedit "nested"
start(x,who)
 if x=1 do  ;two SPACE after do
 . write "hello",!
 . write who
 else  do  ;two SPACE after else and do
 . write "bye",!
 . write who
 quit

GTM>zlink "nested"

GTM>do start^nested(1,"world")
hello
world
GTM>do start^nested(0,"world")
bye
world
operators for string' comparison
These operators are a little bit strange comparing to other languages
GTM>WRITE "A"="B"; compare if two string are equal
0
GTM>WRITE "C"="C"
1
GTM>WRITE "A"["B"; this is same as contains in other language
0
GTM>WRITE "ABC"["C"
1
GTM>WRITE "A"]"B"; this is same as > in other language
0
GTM>WRITE "B"]"A"
1
NOT operator can applied to either expression or other operator
GTM>write "A"="B" 
0
GTM>write '("A"="B")
1
GTM>write "A"'="B"
1

No comments: