Last active
May 3, 2019 21:39
-
-
Save 0xF6/5b9977ee0e4b73c4dc5d76fa6c91646f to your computer and use it in GitHub Desktop.
Mini Calculator
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
namespace Calculator | |
{ | |
using static System.Console; | |
using Sprache; | |
using System.Linq; | |
internal class Program | |
{ | |
public static void Main(string[] args) | |
{ | |
IOperation<int> Build() | |
=> Operation.token.Token().Parse(args.First()); | |
WriteLine($"Result: {Build().Calc()}"); | |
} | |
} | |
public enum OperationType : ushort | |
{ | |
Mul = 42, Div = 47, | |
Sum = 43, Sub = 45 | |
} | |
public struct Operation : IOperation<int> | |
{ | |
public int Value1, Value2; | |
public OperationType Type { get; set; } | |
public int Calc() | |
{ | |
switch (Type) | |
{ | |
case OperationType.Div: return Value1 / Value2; | |
case OperationType.Mul: return Value1 * Value2; | |
case OperationType.Sum: return Value1 + Value2; | |
case OperationType.Sub: return Value1 - Value2; | |
default: return default; | |
} | |
} | |
public static unsafe implicit operator Operation((int n1, int n2, ushort op) raw) => *(Operation*)&raw.n1; | |
public static Parser<Operation> token = | |
from num1 in Parse.Number | |
from op in Parse.Chars('+', '-', '/', '*') | |
from num2 in Parse.Number | |
select (Operation)(int.Parse(num1), int.Parse(num1), op); | |
} | |
public interface IOperation<out T> | |
{ | |
OperationType Type { get; set; } | |
T Calc(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment