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
use crate::errors::Error;
use crate::eval::Eval;
use crate::parse::Parser;
pub struct Calculator {
parser: Parser,
eval: Eval,
}
impl Calculator {
pub fn new() -> Self {
Self {
parser: Parser::new(),
eval: Eval::new(),
}
}
pub fn calculate_line(&self, input: &str) -> Result<f64, Error> {
self.parser
.parse_line(input)
.and_then(|exp| self.eval.eval(&exp))
}
}
impl Default for Calculator {
fn default() -> Self {
Calculator::new()
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::errors::EvalError;
#[test]
fn calculate_line() {
let c = calculator();
assert_eq!(c.calculate_line("1 + 2"), Ok(3.));
assert_eq!(c.calculate_line("-2 * -2"), Ok(4.));
assert_eq!(c.calculate_line("sqrt(sqrt(16)) + 10"), Ok(12.));
}
#[test]
fn divide_by_zero() {
let c = calculator();
assert_eq!(
c.calculate_line("1 / 0"),
Err(Error::Eval(EvalError::DivisionByZero))
);
}
fn calculator() -> Calculator {
Calculator::new()
}
}