-
Notifications
You must be signed in to change notification settings - Fork 1
/
Operator.cs
68 lines (56 loc) · 1.76 KB
/
Operator.cs
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
using System;
using System.Collections.Generic;
namespace Calculator
{
public class Operator
{
public delegate double EvaluationDelegate(double x, double y = 0);
/// <summary>
/// Dictionary mapping operator string to a 2-tuple where the first
/// item in the tuple is operator precendence and the second item in
/// the tuple is associativity.
/// </summary>
private readonly Dictionary<string, Tuple<int, string, EvaluationDelegate>> operatorInfo =
new Dictionary<string, Tuple<int, string, EvaluationDelegate>> ()
{
{"#", new Tuple<int, string, EvaluationDelegate>(5, "right", (x, y) => -x)},
{"@", new Tuple<int, string, EvaluationDelegate>(5, "right", (x, y) => x)},
{"^", new Tuple<int, string, EvaluationDelegate>(4, "right", Math.Pow)},
{"*", new Tuple<int, string, EvaluationDelegate>(3, "left", (x, y) => x * y)},
{"/", new Tuple<int, string, EvaluationDelegate>(3, "left", (x, y) => x / y)},
{"+", new Tuple<int, string, EvaluationDelegate>(2, "left", (x, y) => x + y)},
{"-", new Tuple<int, string, EvaluationDelegate>(2, "left", (x, y) => x - y)}
};
private readonly Token op;
public Operator (Token token)
{
this.op = token;
}
public Token Op {
get {
return op;
}
}
public int Precedence {
get {
Tuple<int, string, EvaluationDelegate> tuple;
operatorInfo.TryGetValue (op.Value, out tuple);
return tuple.Item1;
}
}
public string Associativity {
get {
Tuple<int, string, EvaluationDelegate> tuple;
operatorInfo.TryGetValue (op.Value, out tuple);
return tuple.Item2;
}
}
public EvaluationDelegate Operation {
get {
Tuple<int, string, EvaluationDelegate> tuple;
operatorInfo.TryGetValue (op.Value, out tuple);
return tuple.Item3;
}
}
}
}