forked from kontur-edu/git-merge-task
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Calculator.cs
57 lines (54 loc) · 1.44 KB
/
Calculator.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
namespace Kontur.Courses.Git
{
public class Calculator
{
private Maybe<double> lastResult = 0;
public Maybe<double> Calculate(string[] args)
{
if (args.Length == 0)
return lastResult;
if (args.Length == 1)
return lastResult = TryParseDouble(args[0]);
if (args.Length == 2)
{
// Åñëè íå õâàòàåò ïåðâîãî àðãóìåíòà, òî èñïîëüçîâàòü lastResult// Åñëè íå õâàòàåò ïåðâîãî àðãóìåíòà, òî èñïîëüçîâàòü lastResult
// Äîëæíî ðàáîòàòü òàê:
// 2 + 2
//> 4
// + 1
//>5
// return lastResult = Maybe<double>.FromError("Not implemented yet");
var v1 = TryParseDouble(args[1]);
return lastResult = Execute(args[0], lastResult.Value, v1);
}
if (args.Length == 3)
{
var v1 = TryParseDouble(args[0]);
var v2 = TryParseDouble(args[2]);
if (!v1.HasValue) return v1;
if (!v2.HasValue) return v2;
return lastResult = Execute(args[1], v1.Value, v2.Value);
}
return Maybe<double>.FromError("Error input");
}
private Maybe<double> TryParseDouble(string s)
{
double v;
if (double.TryParse(s, out v))
return v;
return Maybe<double>.FromError("Not a number '{0}'", s);
}
private Maybe<double> Execute(string op, double v1, double v2)
{
if (op == "+")
return v1 + v2;
if (op == "-")
return v1 - v2;
if (op == "*")
return v1 - v2;
if (op == "/")
return v1 / v2;
return Maybe<double>.FromError("Unknown operation '{0}'", op);
}
}
}