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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
use crate::context::Context;
use crate::error;
#[derive(Debug, Clone, Copy)]
pub enum BinOp {
Addition,
Subtraction,
Product,
Division,
}
#[derive(Debug, Clone)]
pub enum Expression {
BinOp(BinOp, Box<Expression>, Box<Expression>),
Constant(f32),
Variable(String),
}
use std::str::FromStr;
impl FromStr for Expression {
type Err = error::ParserError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
use crate::parser::parse_expression;
parse_expression(s)
}
}
impl Expression {
fn to_string(&self) -> String {
match self {
Expression::Constant(val) => val.to_string(),
Expression::Variable(var) => var.to_string(),
Expression::BinOp(op, e1, e2) => {
let s1 = e1.to_string();
let s2 = e2.to_string();
match op {
BinOp::Addition => format!("({} + {})", s1, s2),
BinOp::Subtraction => format!("({} - {})", s1, s2),
BinOp::Product => format!("({} * {})", s1, s2),
BinOp::Division => format!("({} / {})", s1, s2),
}
}
}
}
}
use std::fmt::{Display, Error, Formatter};
impl Display for Expression {
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
write!(f, "{}", self.to_string())
}
}
impl Expression {
/// Parses an expression from a string.
///
/// # Examples
/// Basic usage;
///
/// ```
/// use math_engine::expression::Expression;
///
/// let expr = Expression::parse("1.0 + x").unwrap();
/// ```
///
/// # Errors
/// A ParserError is returned by the parser if the string could not be
/// parsed properly.
pub fn parse(s: &str) -> Result<Self, error::ParserError> {
Expression::from_str(s)
}
/// Creates a new constant from a floating point value.
///
/// # Examples
/// Basic usage:
///
/// ```
/// use math_engine::expression::Expression;
///
/// let expr = Expression::constant(2.0);
/// let eval = expr.eval().unwrap();
///
/// assert_eq!(eval, 2.0);
/// ```
pub fn constant(val: f32) -> Self {
Expression::Constant(val)
}
/// Creates a variable.
///
/// # Examples
/// Basic usage:
///
/// ```
/// use math_engine::context::Context;
/// use math_engine::expression::Expression;
///
/// let expr = Expression::variable("x");
/// let ctx = Context::new().with_variable("x", 32.0);
/// let eval = expr.eval_with_context(&ctx).unwrap();
///
/// assert_eq!(eval, 32.0);
/// ```
pub fn variable(name: &str) -> Self {
Expression::Variable(name.to_string())
}
/// Creates an expression representing a binary operation.
fn binary_op(op: BinOp, e1: Expression, e2: Expression) -> Self {
Expression::BinOp(op, Box::new(e1), Box::new(e2))
}
/// Creates a new binary operation which sums two sub-expressions
///
/// # Examples
/// Basic usage:
///
/// ```
/// use math_engine::expression::Expression;
///
/// let expr = Expression::addition(
/// Expression::constant(2.0),
/// Expression::Constant(3.0)
/// );
/// let eval = expr.eval().unwrap();
///
/// assert_eq!(eval, 5.0);
/// ```
pub fn addition(e1: Expression, e2: Expression) -> Self {
Expression::BinOp(BinOp::Addition, Box::new(e1), Box::new(e2))
}
/// Creates a new binary operation which subtracts two sub-expressions
///
/// # Examples
/// Basic usage:
///
/// ```
/// use math_engine::expression::Expression;
///
/// let expr = Expression::subtraction(
/// Expression::constant(2.0),
/// Expression::Constant(3.0)
/// );
/// let eval = expr.eval().unwrap();
///
/// assert_eq!(eval, -1.0);
/// ```
pub fn subtraction(e1: Expression, e2: Expression) -> Self {
Expression::BinOp(BinOp::Subtraction, Box::new(e1), Box::new(e2))
}
/// Creates a new binary operation which multiplies two sub-expressions
///
/// # Examples
/// Basic usage:
///
/// ```
/// use math_engine::expression::Expression;
///
/// let expr = Expression::product(
/// Expression::constant(2.0),
/// Expression::Constant(3.0)
/// );
/// let eval = expr.eval().unwrap();
///
/// assert_eq!(eval, 6.0);
/// ```
pub fn product(e1: Expression, e2: Expression) -> Self {
Expression::BinOp(BinOp::Product, Box::new(e1), Box::new(e2))
}
/// Creates a new binary operation which divides two sub-expressions
///
/// # Examples
/// Basic usage:
///
/// ```
/// use math_engine::expression::Expression;
///
/// let expr = Expression::division(
/// Expression::constant(3.0),
/// Expression::Constant(2.0)
/// );
/// let eval = expr.eval().unwrap();
///
/// assert_eq!(eval, 1.5);
/// ```
pub fn division(e1: Expression, e2: Expression) -> Self {
Expression::BinOp(BinOp::Division, Box::new(e1), Box::new(e2))
}
fn eval_core(&self, ctx: Option<&Context>) -> Result<f32, error::EvalError> {
match self {
Expression::Constant(val) => Ok(*val),
Expression::BinOp(op, e1, e2) => {
let r1 = e1.eval_core(ctx)?;
let r2 = e2.eval_core(ctx)?;
let r = match op {
BinOp::Addition => r1 + r2,
BinOp::Subtraction => r1 - r2,
BinOp::Product => r1 * r2,
BinOp::Division => r1 / r2,
};
if r.is_nan() {
Err(error::EvalError::NotANumber)
} else if r.is_infinite() {
Err(error::EvalError::IsInfinite)
} else {
Ok(r)
}
}
Expression::Variable(name) => match ctx {
Some(ctx) => match ctx.get_variable(name) {
Ok(r) => Ok(r),
Err(_) => Err(error::EvalError::VariableNotFound(name.clone())),
},
None => Err(error::EvalError::NoContextGiven),
},
}
}
/// Evaluates the expression into a floating point value without a context.
///
/// As of now, floating point value is the only supported evaluation. Please
/// note that it is therefore subject to approximations due to some values
/// not being representable.
///
/// # Examples
///
/// ```
/// use math_engine::context::Context;
/// use math_engine::expression::Expression;
///
/// // Expression is (1 - 5) + (2 * (4 + 6))
/// let expr = Expression::addition(
/// Expression::subtraction(
/// Expression::constant(1.0),
/// Expression::constant(5.0)
/// ),
/// Expression::product(
/// Expression::constant(2.0),
/// Expression::addition(
/// Expression::constant(4.0),
/// Expression::constant(6.0)
/// )
/// )
/// );
/// let eval = expr.eval().unwrap();
///
/// assert_eq!(eval, 16.0);
/// ```
///
/// # Errors
///
/// If any intermediary result is not a number of is infinity, an error is
/// returned.
/// If the expression contains a variable, an error is returned
pub fn eval(&self) -> Result<f32, error::EvalError> {
self.eval_core(None)
}
/// Evaluates the expression into a floating point value with a given context.
///
/// As of now, floating point value is the only supported evaluation. Please
/// note that it is therefore subject to approximations due to some values
/// not being representable.
///
/// # Examples
///
/// ```
/// use math_engine::context::Context;
/// use math_engine::expression::Expression;
///
/// // Expression is (1 / (1 + x))
/// let expr = Expression::division(
/// Expression::constant(1.0),
/// Expression::addition(
/// Expression::constant(1.0),
/// Expression::variable("x"),
/// )
/// );
/// let ctx = Context::new().with_variable("x", 2.0);
/// let eval = expr.eval_with_context(&ctx).unwrap();
///
/// assert_eq!(eval, 1.0/3.0);
/// ```
///
/// # Errors
///
/// If any intermediary result is not a number of is infinity, an error is
/// returned.
/// If the expression contains a variable but the context does not define all
/// the variables, an error is returned.
pub fn eval_with_context(&self, ctx: &Context) -> Result<f32, error::EvalError> {
self.eval_core(Some(ctx))
}
/// Calculates the derivative of an expression.
///
/// # Examples
/// Basic usage:
///
/// ```
/// use math_engine::expression::Expression;
/// use std::str::FromStr;
///
/// //Represents y + 2x
/// let expr = Expression::from_str("1.0 * y + 2.0 * x");
///
/// //Represents y + 2
/// let deri = expr.derivative("x");
/// ```
pub fn derivative(&self, deriv_var: &str) -> Self {
match self {
Expression::Constant(_) => Expression::constant(0.0),
Expression::Variable(var) => {
if var.as_str() == deriv_var {
Expression::constant(1.0)
} else {
Expression::variable(var.as_str())
}
}
Expression::BinOp(op, e1, e2) => {
let deriv_e1 = e1.derivative(deriv_var);
let deriv_e2 = e2.derivative(deriv_var);
match op {
BinOp::Addition => Expression::addition(deriv_e1, deriv_e2),
BinOp::Subtraction => Expression::subtraction(deriv_e1, deriv_e2),
BinOp::Product => Expression::addition(
Expression::product(*e1.clone(), deriv_e2),
Expression::product(deriv_e1, *e2.clone()),
),
BinOp::Division => Expression::division(
Expression::subtraction(
Expression::product(*e2.clone(), deriv_e1),
Expression::product(deriv_e2, *e1.clone()),
),
Expression::product(*e2.clone(), *e2.clone()),
),
}
}
}
}
/// Simplifies the expression by applying constant propagation.
///
/// # Examples
/// Basic usage:
///
/// ```
/// use math_engine::expression::Expression;
///
/// let expr = Expression::parse("1.0 * y + 0.0 * x + 2.0 / 3.0").unwrap();
///
/// //Represents "y + 0.66666..."
/// let simp = expr.constant_propagation().unwrap()
/// ```
///
/// # Errors
/// An EvalError (DivisionByZero) can be returned if the partial evaluation
/// of the expression revealed a division by zero.
pub fn constant_propagation(&self) -> Result<Self, error::EvalError> {
match self {
Expression::Constant(_) => Ok(self.clone()),
Expression::Variable(_) => Ok(self.clone()),
Expression::BinOp(op, e1, e2) => {
let e1 = e1.constant_propagation()?;
let e2 = e2.constant_propagation()?;
match (op, &e1, &e2) {
(_, Expression::Constant(v1), Expression::Constant(v2)) => match op {
BinOp::Addition => Ok(Expression::constant(v1 + v2)),
BinOp::Subtraction => Ok(Expression::constant(v1 - v2)),
BinOp::Product => Ok(Expression::constant(v1 * v2)),
BinOp::Division => Ok(Expression::constant(v1 / v2)),
},
(BinOp::Product, Expression::Constant(v), _) if *v == 1.0 => Ok(e2),
(BinOp::Product, _, Expression::Constant(v)) if *v == 1.0 => Ok(e1),
(BinOp::Division, _, Expression::Constant(v)) if *v == 1.0 => Ok(e1),
(_, Expression::Constant(v), _) if *v == 0.0 => match op {
BinOp::Addition => Ok(e2),
BinOp::Subtraction => unimplemented!(),
BinOp::Product => Ok(Expression::constant(0.0)),
BinOp::Division => Ok(Expression::constant(0.0)),
},
(_, _, Expression::Constant(v)) if *v == 0.0 => match op {
BinOp::Addition => Ok(e1),
BinOp::Subtraction => Ok(e1),
BinOp::Product => Ok(Expression::constant(0.0)),
BinOp::Division => Err(error::EvalError::DivisionByZero),
},
_ => Ok(Expression::binary_op(*op, e1, e2)),
}
}
}
}
}
use std::ops::{Add, Sub, Mul, Div};
macro_rules! expression_impl_trait {
($tr:ident, $tr_fun:ident, $fun:ident) => {
impl $tr for Expression {
type Output = Self;
fn $tr_fun(self, other: Self) -> Self::Output {
Expression::$fun(self, other)
}
}
//impl {$t}rAssign for Expression {
// fn $tr_fun_assign(&mut self, other: Self) {
// *self = Expression::$fun(self, other)
// }
//}
}
}
expression_impl_trait!(Add, add, addition);
expression_impl_trait!(Sub, sub, subtraction);
expression_impl_trait!(Mul, mul, product);
expression_impl_trait!(Div, div, division);