This repository was archived by the owner on Jun 23, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathNumber.cs
More file actions
47 lines (35 loc) · 1.29 KB
/
Copy pathNumber.cs
File metadata and controls
47 lines (35 loc) · 1.29 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
using System;
using Knight.Ops;
namespace Knight
{
public class Number : Literal<long>, IAdd, ISub, IMul, IDiv, IMod, IPow, IComparable<IValue>
{
public Number(long data) : base(data) {}
public static Number Parse(Stream stream) {
var contents = stream.TakeWhileIfStartsWith(char.IsDigit);
return contents == null ? null : new Number(long.Parse(contents));
}
public override void Dump() => Console.Write($"Number({this})");
public override bool ToBoolean() => _data != 0;
public override long ToNumber() => _data;
public int CompareTo(IValue other) => _data.CompareTo(other.ToNumber());
public IValue Add(IValue rhs) => new Number(_data + rhs.ToNumber());
public IValue Sub(IValue rhs) => new Number(_data - rhs.ToNumber());
public IValue Mul(IValue rhs) => new Number(_data * rhs.ToNumber());
public IValue Div(IValue rhs) {
var rlong = rhs.ToNumber();
if (rlong == 0) {
throw new RuntimeException("Cannot divide by zero!");
}
return new Number(_data / rlong);
}
public IValue Mod(IValue rhs) {
var rlong = rhs.ToNumber();
if (rlong == 0) {
throw new RuntimeException("Cannot modulo by zero!");
}
return new Number(_data % rlong);
}
public IValue Pow(IValue rhs) => new Number((long) Math.Pow(_data, rhs.ToNumber()));
}
}