Skip to content

Basic Variants

NN--- edited this page Apr 11, 2012 · 4 revisions

Basic Variants

  • Category: Defining Types
  • Description: Variants give a way of building types from the disjoint union of two or more existing types. This sample shows how to build one such type and how to decompose its values.
  • Code:
using System;
using System.Console;
using Nemerle;
using System.Linq;

[Record]
class Wheel 
{
  radius :  double;  // radius of wheel, inches
  
  public override ToString() : string
  {
    radius.ToString()
  }

}

variant Cycle 
{
  | Unicycle { wheel : Wheel; }
  | Bicycle { front : Wheel; back : Wheel; }

  public override ToString() : string
  {
    match (this)
    {
      | Unicycle(r)     => $"Unicycle, one wheel, radius = $r"
      | Bicycle(r1, r2) => $"Bicycle, two wheels, front = $r1, back = $r2"
    }
  }

}


module UnionSample1
{

  Main() : void
  {
    def veryBigWheel = Wheel(26.0);
    def bigWheel     = Wheel(13.0);
    def smallWheel   = Wheel(6.0);

    def pennyFarthing = Cycle.Bicycle(veryBigWheel, smallWheel);
    def racer         = Cycle.Bicycle(bigWheel, bigWheel);
    def kidsBike      = Cycle.Bicycle(smallWheel, smallWheel);

    WriteLine(pennyFarthing);
    WriteLine(racer);
    WriteLine(kidsBike);
  }

}
  • Execution Result:
Bicycle, two wheels, front = 26, back = 6
Bicycle, two wheels, front = 13, back = 13
Bicycle, two wheels, front = 6, back = 6

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

Clone this wiki locally