2.1.3. Macro functions

You can also define a macro function. The expansion rules are: the body is not expanded during definition. At the point of call, the arguments are expanded and then substituted into the body, then the body is expanded.
Start C++ section to tut/examples/mac124.flx[1 /1 ]
     1: include "std";
     2: 
     3: // a basic expression macro without parameters
     4: macro fun x() =  {print 1; endl;};
     5: x;
     6: 
     7: // an expression macro with one argument
     8: macro fun h(z) = z + z;
     9: print (h 1); endl;
    10: 
    11: // an expression macro denoting a procedure
    12: macro fun f(a) = { print a; endl; };
    13: f 1;
    14: f 2;
    15: 
    16: // nastier example of rescanning
    17: macro fun a() = b c;
    18: macro fun b(x) = f;
    19: a() 1;
    20: // (b c) 1;
    21: // f 1;
    22: // { print 1; endl; };
    23: // call {print 1; endl; } ();
    24: 
    25: // finally: recursion
    26: macro fun j(i) =
    27:    if(i>0) then i + j(i-1)
    28:    else 0 endif;
    29: print  (j 5); // 5 + 4 + 3 + 2 + 1 = 16
    30: endl;
    31: 
    32: val q=1;
    33: macro fun z(q) = q;
    34: print (z q); endl;
    35: 
End C++ section to tut/examples/mac124.flx[1]
It is vital to understand that macros cannot break syntactically established precedence rules. In the last example, a 1 expands to (b c) 1, which expands to f 1. Substitutions are implemented by manipulation of the abstract syntax tree (AST), not token pasting or string manipulation.