Last active
August 29, 2015 14:05
-
-
Save javi830810/7850a37f9c780cff5835 to your computer and use it in GitHub Desktop.
Peano Numbers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
namespace PeanoNumbers | |
{ | |
public class PeanoNumber | |
{ | |
private PeanoNumber _base; | |
public PeanoNumber ():this(null) | |
{ | |
} | |
public PeanoNumber (PeanoNumber x) | |
{ | |
this._base = x; | |
} | |
public PeanoNumber (int x) | |
{ | |
if(x >= 0) | |
this._base = new PeanoNumber(x-1); | |
} | |
public bool IsZero{ get { return this._base == null; } } | |
public bool IsOne{ get { return !IsZero && this._base.IsZero; } } | |
public static PeanoNumber Zero{ get { return new PeanoNumber (); } } | |
public int ToNatural(){ | |
if (this._base == null) | |
return 0; | |
else | |
return 1 + this._base.ToNatural (); | |
} | |
public PeanoNumber Sum(PeanoNumber y){ | |
if (y.IsZero) | |
return this; | |
if (this.IsZero) | |
return y; | |
return new PeanoNumber(this + y._base); | |
} | |
public static PeanoNumber operator +(PeanoNumber p1, PeanoNumber p2) | |
{ | |
return p1.Sum (p2); | |
} | |
public PeanoNumber Difference(PeanoNumber y){ | |
if (this.IsZero && !y.IsZero) | |
throw new Exception("Peano doesnt have negative numbers"); | |
if (y.IsZero) | |
return this; | |
return this._base - y._base; | |
} | |
public static PeanoNumber operator -(PeanoNumber p1, PeanoNumber p2) | |
{ | |
return p1.Difference(p2); | |
} | |
public PeanoNumber Product(PeanoNumber y){ | |
if (this.IsZero || y.IsZero) | |
return Zero; | |
return this + this* y._base; | |
} | |
public static PeanoNumber operator *(PeanoNumber p1, PeanoNumber p2) | |
{ | |
return p1.Product(p2); | |
} | |
public PeanoNumber Division(PeanoNumber y){ | |
if (this.IsZero) | |
return Zero; | |
if (y.IsZero) | |
throw new Exception ("Division by zero doesnt exists"); | |
return new PeanoNumber ((this._base - y._base) / y); | |
} | |
public static PeanoNumber operator /(PeanoNumber p1, PeanoNumber p2) | |
{ | |
return p1.Division(p2); | |
} | |
public override bool Equals(object y){ | |
if (!(y is PeanoNumber)) | |
return false; | |
var toCompare = y as PeanoNumber; | |
if (toCompare.IsZero && !this.IsZero) | |
return false; | |
else if (!toCompare.IsZero && this.IsZero) | |
return false; | |
else | |
return this._base.Equals (toCompare._base); | |
} | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment