Initialization macros - vilinski/nemerle GitHub Wiki

Initialization macros

  • Category: Macros
  • Description: Using New Object macro for entity initialization
  • Code:
using System;
using System.Collections.Generic;
using System.Console;

using Nemerle.Extensions;

class Point
{
  public mutable X : int;
  public mutable Y : int;

  public override ToString() : string { $"$X, $Y" }
}

class Rectangle
{
  public this()
  {
    A = Point();
    B = Point();
  }

  public A : Point { get; set; }
  public B : Point { get; set; }

  public override ToString() : string { $"$A, $B" }
}

class Figure
{
  public Points : List[Point]
  {
    points : List[Point] = List();
    get { points }
  }
}

module Program
{
  Main() : void
  {
    // simple initializer
    WriteLine(Point() <-
    {
      X = 10;
      Y = 20;
    });

    // nested initializer
    WriteLine(Rectangle() <-
    {
      A <- { X += 1; Y = 2; };
      B = Point() <- (X -= 3, Y = 4);
    });

    // collection initializer
    def points = List() <-
    [
      Point() <- (X = 1, Y = 1),
      Point() <- (X = 2, Y = 2),
      Point() <- (X = 3, Y = 3),
    ];
    foreach(p in points)
      WriteLine(p);

    // dictionary initializer
    def table = Dictionary() <-
    [
      "a" = Point() <- X = 10,
      "b" = Point() <- X = 20,
      ("c", Point() <- X = 30),
      ("d", Point() <- X = 40)
    ];
    WriteLine(table["b"]);
    WriteLine(table["d"]);

    // nested collection initializer
    def figure = Figure() <- Points ::=
    [
      Point() <- X = 100,
      Point() <- X = 200
    ];
    foreach(p in figure.Points)
      WriteLine(p);
  }
}
  • Execution Result:
10, 20
1, 2, -3, 4
1, 1
2, 2
3, 3
20, 0
40, 0
100, 0
200, 0

[Copyright ©](Terms of use, legal notice)