Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //**************************************************************
- // File: Main.n
- using System.Console;
- using LazydefMacroLibrary;
- module Program
- {
- Main() : void
- {
- def LazyTest(n)
- {
- WriteLine($"Side effect with $(n).");
- n
- }
- // Implementation of 'lazy mutable' and 'lazy def' macros pastebined below (LazyTestMacroLibrary.n)
- lazy mutable mutableVar = LazyTest(42);
- lazy def immutableVar : int = LazyTest(19);
- WriteLine("Nemerle lazy evaluation test.");
- WriteLine($"Hi! 'mutableVar' value now is $(mutableVar)");
- WriteLine($"Hi! 'immutableVar' value now is $(immutableVar)");
- _ = ReadLine();
- }
- }
- **************************************************************
- Output:
- Nemerle lazy evaluation test.
- Side effect with 42.
- Hi! 'mutableVar' value now is 42
- Side effect with 19.
- Hi! 'immutableVar' value now is 19
- //**************************************************************
- // File: LazyTestMacroLibrary.n
- using Nemerle;
- using Nemerle.Compiler;
- using Nemerle.Compiler.Parsetree;
- namespace LazyTestMacroLibrary
- {
- public macro lazymutable(expr)
- syntax ("lazy", "mutable", expr)
- {
- LazyMutableMacroImpl.DoTransform(Macros.ImplicitCTX(), expr)
- }
- module LazyMutableMacroImpl
- {
- public DoTransform(typer : Typer, expr : PExpr) : PExpr
- {
- Macros.DefineCTX(typer);
- match(expr)
- {
- | <[ ($v : $t = $w) ]> => <[mutable $v : LazyValue[$t] = (lazy($w))]>
- | <[ ($v = $w) ]> => <[mutable $v = (lazy($w))]>
- | _ => Message.Error(expr.Location, $"Expected mutable declaration with assignment, got: $expr");
- PExpr.Error(expr.Location)
- }
- }
- }
- public macro lazydef(expr)
- syntax ("lazy", "def", expr)
- {
- LazydefMacroImpl.DoTransform(Macros.ImplicitCTX(), expr)
- }
- module LazydefMacroImpl
- {
- public DoTransform(typer : Typer, expr : PExpr) : PExpr
- {
- Macros.DefineCTX(typer);
- match(expr)
- {
- | <[ ($v : $t = $w) ]> => <[def $v : LazyValue[$t] = (lazy($w))]>
- | <[ ($v = $w) ]> => <[def $v = (lazy($w))]>
- | _ => Message.Error(expr.Location, $"Expected def declaration with assignment, got: $expr");
- PExpr.Error(expr.Location)
- }
- }
- }
- }
Add Comment
Please, Sign In to add comment