Guest User

Untitled

a guest
Jan 24th, 2018
115
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.32 KB | None | 0 0
  1. //**************************************************************
  2. // File: Main.n
  3.  
  4. using System.Console;
  5. using LazydefMacroLibrary;
  6.  
  7. module Program
  8. {
  9.   Main() : void
  10.   {
  11.     def LazyTest(n)
  12.     {
  13.       WriteLine($"Side effect with $(n).");
  14.       n
  15.     }
  16.    
  17.     // Implementation of 'lazy mutable' and 'lazy def' macros pastebined below (LazyTestMacroLibrary.n)
  18.     lazy mutable mutableVar = LazyTest(42);
  19.     lazy def immutableVar : int = LazyTest(19);
  20.    
  21.     WriteLine("Nemerle lazy evaluation test.");
  22.     WriteLine($"Hi! 'mutableVar' value now is $(mutableVar)");
  23.     WriteLine($"Hi! 'immutableVar' value now is $(immutableVar)");
  24.     _ = ReadLine();
  25.   }
  26. }
  27.  
  28. **************************************************************
  29. Output:
  30.  
  31. Nemerle lazy evaluation test.
  32. Side effect with 42.
  33. Hi! 'mutableVar' value now is 42
  34. Side effect with 19.
  35. Hi! 'immutableVar' value now is 19
  36.  
  37. //**************************************************************
  38. // File: LazyTestMacroLibrary.n
  39.  
  40. using Nemerle;
  41. using Nemerle.Compiler;
  42. using Nemerle.Compiler.Parsetree;
  43.  
  44. namespace LazyTestMacroLibrary
  45. {
  46.   public macro lazymutable(expr)
  47.   syntax ("lazy", "mutable", expr)
  48.   {
  49.     LazyMutableMacroImpl.DoTransform(Macros.ImplicitCTX(), expr)
  50.   }
  51.    
  52.   module LazyMutableMacroImpl
  53.   {
  54.     public DoTransform(typer : Typer, expr : PExpr) : PExpr
  55.     {
  56.       Macros.DefineCTX(typer);
  57.       match(expr)
  58.       {
  59.         | <[ ($v : $t = $w) ]> => <[mutable $v : LazyValue[$t] = (lazy($w))]>
  60.         | <[ ($v = $w) ]> => <[mutable $v = (lazy($w))]>
  61.         | _ => Message.Error(expr.Location, $"Expected mutable declaration with assignment, got: $expr");
  62.                PExpr.Error(expr.Location)
  63.       }
  64.     }
  65.   }
  66.  
  67.   public macro lazydef(expr)
  68.   syntax ("lazy", "def", expr)
  69.   {
  70.     LazydefMacroImpl.DoTransform(Macros.ImplicitCTX(), expr)
  71.   }
  72.    
  73.   module LazydefMacroImpl
  74.   {
  75.     public DoTransform(typer : Typer, expr : PExpr) : PExpr
  76.     {
  77.       Macros.DefineCTX(typer);
  78.       match(expr)
  79.       {
  80.         | <[ ($v : $t = $w) ]> => <[def $v : LazyValue[$t] = (lazy($w))]>
  81.         | <[ ($v = $w) ]> => <[def $v = (lazy($w))]>
  82.         | _ => Message.Error(expr.Location, $"Expected def declaration with assignment, got: $expr");
  83.                PExpr.Error(expr.Location)
  84.       }
  85.     }
  86.   }
  87. }
Add Comment
Please, Sign In to add comment