-
Notifications
You must be signed in to change notification settings - Fork 89
Simple expression evaluator
Alex Zimin edited this page Jul 11, 2011
·
3 revisions
The macro source code, macro.n:
using Nemerle.Compiler;
macro myeval (expr)
{
def r = System.Random ();
def eval (expr) {
| <[ $e1 + $e2 ]> => eval (e1) + eval (e2)
| <[ $e1 * $e2 ]> => eval (e1) * eval (e2)
| <[ $e1 / $e2 ]> => eval (e1) / eval (e2)
| <[ $e1 - $e2 ]> => eval (e1) - eval (e2)
| <[ rand ]> => r.Next () % 42
| <[ $(k : int) ]> => k
| e =>
Message.Error ($ "invalid expression to myeval: $e");
0
}
def res = eval (expr);
Message.Warning ($"myeval($expr) = $res");
<[ $(res : int) ]>
}
Example usage, use.n:
System.Console.WriteLine (myeval (2 + 2));
System.Console.WriteLine (myeval (2 + 8 * rand));
Compilation and running:
ncc -r:Nemerle.Compiler -t:dll -o:macro.dll macro.n ncc -r:macro.dll use.n ./out.exe
and the results, first warnings from the compiler:
use.n:1:27: warning: myeval(2 + 2) = 4 use.n:2:27: warning: myeval(2 + 8 * rand) = 162
and then the output:
4 162