-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathParser.cs
More file actions
39 lines (32 loc) · 1.14 KB
/
Parser.cs
File metadata and controls
39 lines (32 loc) · 1.14 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
namespace reverse_polish_notation;
public class Parser: IParser
{
private IList<string> _supportedOperators;
public IList<string> SupportedOperators { get => _supportedOperators; set => _supportedOperators = value; }
public Parser()
{
_supportedOperators = new List<string> { "+", "-", "*", "/", "^", "sqrt" };
}
public Parser(IList<string> supportedOperators)
{
_supportedOperators = supportedOperators;
}
public IList<string> Tokenize(string expression)
{
string[] expressions = expression.Split(' ');
var list = new List<string>();
foreach(string s in expressions) list.Add(s);
return list;
}
public IList<Token> Lex(IList<string> expression)
{
var tokens = new List<Token>();
foreach(string e in expression)
{
if (e.All(char.IsDigit)) tokens.Add(new Token(TokenType.Number, e));
else if (_supportedOperators.Contains(e)) tokens.Add(new Token(TokenType.Operator, e));
else throw new InvalidOperationException($"Unknown operation: {e}");
}
return tokens;
}
}