Skip to content

Define operator

NN--- edited this page Apr 18, 2012 · 5 revisions

Define operator

  • Category: Defining Operator
  • Description: Define operators in a class.
  • Code:
using System;
using System.Console;
using Nemerle;

[Record]
class Fraction 
{
      // n: Numerator of fraction.
  numerator : uint;
      // d: Denominator of fraction.
  denominator : uint;

  static hcf(a : uint, b : uint) : uint
  {
    if (a == 0u) b else 
    if (a < b) hcf(a, b - a)
    else hcf(a - b, b)
  } 
  // Produce a string representation. If the
  // denominator is "1", do not display it.
  public override ToString() : string
  {
    if (denominator == 1) $"$numerator" else $"$numerator/$denominator"
  }

  // Add two fractions.
  public static @+(f1 : Fraction, f2 : Fraction) : Fraction
  {
    def nTemp = f1.numerator * f2.denominator + f2.numerator * f1.denominator;
    def dTemp = f1.denominator * f2.denominator;
    def hcfTemp = hcf(nTemp, dTemp);
    Fraction(nTemp / hcfTemp, dTemp / hcfTemp)
  }
  
  // Adds a fraction and a positive integer.
  public static @+(f1: Fraction, i : uint) : Fraction
  {
    def nTemp = f1.numerator + i * f1.denominator;
    def dTemp = f1.denominator;
    def hcfTemp = hcf(nTemp, dTemp);
    Fraction(nTemp / hcfTemp, dTemp / hcfTemp)
  }
  
  // Adds a positive integer and a fraction.
  public static @+(i : uint, f2: Fraction) : Fraction
  {
    def nTemp = f2.numerator + i * f2.denominator;
    def dTemp = f2.denominator;
    def hcfTemp = hcf(nTemp, dTemp);
    Fraction(nTemp / hcfTemp, dTemp / hcfTemp)
  }
}


def fraction1 = Fraction(3u, 4u);
def fraction2 = Fraction(1u, 2u);
def result1 = fraction1 + fraction2;
def result2 = fraction1 + 1u;
def result3 = 2 + fraction1;
WriteLine($"result1 = $result1");
WriteLine($"result2 = $result2");
WriteLine($"result3 = $result3")
  • Execution Result:
result1 = 5/4
result2 = 7/4
result3 = 11/4

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

Clone this wiki locally