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
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
/* Clippy Config */
#![allow(clippy::std_instead_of_core)]
/* Built-in imports */
use core::{fmt, ptr};
use std::collections::{HashMap, HashSet};
/* Crate imports */
use crate::{
element::Element,
element::Simplify,
token::Operator,
utils::{
factorial::factorial,
hidden_macros::{trust_me, yeet},
},
};
/// Represents a mathematical expression and its variables.
#[derive(Debug, PartialEq, Clone)]
#[non_exhaustive]
pub struct Xprs<'a> {
/// The root element of the expression.
pub root: Element<'a>,
/// The set of variables present in the expression.
pub vars: HashSet<&'a str>,
}
impl<'input> TryFrom<&'input str> for Xprs<'input> {
type Error = crate::ParseError;
#[inline]
fn try_from(value: &'input str) -> Result<Self, Self::Error> {
let parser = crate::Parser::default();
let xprs = parser.parse(value);
xprs
}
}
impl fmt::Display for Xprs<'_> {
#[inline]
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(fmt, "{}", self.root)
}
}
impl Xprs<'_> {
/// Evaluates the expression using the provided variable values.
/// Returns an [`f64`] if the evaluation is successful, or an [`EvalError`] if an error occurs.
///
/// # Errors
///
/// An [`EvalError`] is returned if a variable is not provided.
///
/// # Example
///
/// ```
/// use xprs::Xprs;
/// use std::collections::HashMap;
///
/// let expression = "2 * x + y";
/// let xprs = Xprs::try_from(expression)?;
///
/// let mut variable_values = HashMap::new();
/// variable_values.insert("x", 3.0);
/// variable_values.insert("y", 2.0);
///
/// let result = xprs.eval(&variable_values);
/// assert_eq!(result, Ok(8.0));
///
/// // we didn't provide the variables, so this should fail
/// let failed_eval = xprs.eval(&HashMap::new());
/// assert!(failed_eval.is_err());
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[inline]
pub fn eval(
&self,
variables: &HashMap<&str, f64>,
) -> Result<f64, EvalError> {
XprsImpl::new(variables).eval_element(&self.root)
}
/// Evaluates the expression using the provided variable values without error handling.
/// Returns an [`f64`] if the evaluation is successful, or panics if an error occurs.
///
/// # Panic
///
/// Use with caution, as it may panic if variable(s) are missing.
///
/// # Example
///
/// ```
/// use xprs::Xprs;
/// # use std::panic;
/// # macro_rules! assert_panic {
/// # ($($t:tt)*) => {
/// # panic::catch_unwind(panic::AssertUnwindSafe(|| {
/// # $($t)*
/// # })).is_err()
/// # }
/// # }
/// use std::collections::HashMap;
///
/// let expression = "2 * x + y";
/// let xprs = Xprs::try_from(expression)?;
///
/// let mut variable_values = HashMap::new();
/// variable_values.insert("x", 3.0);
/// variable_values.insert("y", 2.0);
///
/// let result = xprs.eval_unchecked(&variable_values);
/// assert_eq!(result, 8.0);
///
/// // we didn't provide the variables, so this should panic
/// assert_panic!(xprs.eval_unchecked(&HashMap::new()));
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[inline]
#[must_use]
pub fn eval_unchecked(&self, variables: &HashMap<&str, f64>) -> f64 {
XprsImpl::new(variables).eval_element_unchecked(&self.root)
}
/// Simplifies the expression in-place for a single variable.
///
/// # Example
///
/// ```
/// use xprs::Xprs;
///
/// let expression = "2 * x + y";
/// let mut xprs = Xprs::try_from(expression)?;
///
/// assert_eq!(format!("{xprs}"), "((2 * x) + y)");
/// assert_eq!(xprs.vars, ["x", "y"].into());
///
/// xprs.simplify_for_in_place(("x", 3.0));
///
/// assert_eq!(format!("{xprs}"), "(6 + y)");
/// assert_eq!(xprs.vars, ["y"].into());
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[inline]
pub fn simplify_for_in_place(&mut self, var: (&str, f64)) {
let mut tmp = trust_me!(ptr::read(&self.root));
tmp = tmp.simplify_for(var);
trust_me!(ptr::write(&mut self.root, tmp););
self.vars.remove(var.0);
}
/// Simple wrapper around [`Xprs::eval`] that doesn't require any variables.
/// This will obviously fail if the expression contains variables.
///
/// # Errors
///
/// An [`EvalError`] is returned if the expression contains variables.
#[inline]
pub fn eval_no_vars(&self) -> Result<f64, EvalError> {
self.eval(&[].into())
}
/// Simple wrapper around [`Xprs::eval_unchecked`] that doesn't require any variables.
/// This will obviously fail if the expression contains variables.
///
/// # Panic
///
/// Use with caution, as it may panic if the expression contains variables.
#[inline]
#[must_use]
pub fn eval_no_vars_unchecked(&self) -> f64 {
self.eval_unchecked(&[].into())
}
/// Simplifies the expression in-place for a single variable and returns the expression.
///
/// # Example
///
/// ```
/// use xprs::Xprs;
///
/// let expression = "2 * x + y";
/// let xprs = Xprs::try_from(expression)?;
///
/// assert_eq!(format!("{xprs}"), "((2 * x) + y)");
/// assert_eq!(xprs.vars, ["x", "y"].into());
///
/// let simplified_xprs = xprs.simplify_for(("x", 3.0));
///
/// assert_eq!(format!("{simplified_xprs}"), "(6 + y)");
/// assert_eq!(simplified_xprs.vars, ["y"].into());
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[inline]
#[must_use]
pub fn simplify_for(mut self, var: (&str, f64)) -> Self {
self.simplify_for_in_place(var);
self
}
/// Simplifies the expression in-place for multiple variables.
///
/// # Example
///
/// ```
/// use xprs::Xprs;
///
/// let expression = "2 * x + y + 4z";
/// let mut xprs = Xprs::try_from(expression)?;
///
/// assert_eq!(format!("{xprs}"), "(((2 * x) + y) + (4 * z))");
/// assert_eq!(xprs.vars, ["x", "y", "z"].into());
///
/// xprs.simplify_for_multiple_in_place(&[("x", 3.0), ("z", 2.0)]);
///
/// assert_eq!(format!("{xprs}"), "((6 + y) + 8)");
/// assert_eq!(xprs.vars, ["y"].into());
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[inline]
pub fn simplify_for_multiple_in_place(&mut self, vars: &[(&str, f64)]) {
// rewriting `simplify_for_in_place` to avoid dozens of `ptr::read` and `ptr::write`
let mut tmp = trust_me!(ptr::read(&self.root));
for &var in vars {
tmp = tmp.simplify_for(var);
self.vars.remove(var.0);
}
trust_me!(ptr::write(&mut self.root, tmp););
}
/// Simplifies the expression in-place for multiple variables and returns the expression.
///
/// # Example
///
/// ```
/// use xprs::Xprs;
///
/// let expression = "2 * x + y + 4z";
/// let xprs = Xprs::try_from(expression)?;
///
/// assert_eq!(format!("{xprs}"), "(((2 * x) + y) + (4 * z))");
/// assert_eq!(xprs.vars, ["x", "y", "z"].into());
///
/// let simplified_xprs = xprs.simplify_for_multiple(&[("x", 3.0), ("z", 2.0)]);
///
/// assert_eq!(format!("{simplified_xprs}"), "((6 + y) + 8)");
/// assert_eq!(simplified_xprs.vars, ["y"].into());
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[inline]
#[must_use]
pub fn simplify_for_multiple(mut self, vars: &[(&str, f64)]) -> Self {
self.simplify_for_multiple_in_place(vars);
self
}
}
/// An internal struct used for evaluating expressions.
///
/// This struct is responsible for handling the evaluation of individual elements within an expression.
/// It is used by the [`Xprs`] struct to perform evaluations with respect to a given set of variable values.
struct XprsImpl<'a> {
/// A reference to the map of variables and their corresponding values.
variables: &'a HashMap<&'a str, f64>,
}
impl XprsImpl<'_> {
/// Creates a new [`XprsImpl`] instance.
const fn new<'a>(variables: &'a HashMap<&str, f64>) -> XprsImpl<'a> {
XprsImpl { variables }
}
/// Evaluates an element within an expression and returns the result.
fn eval_element(&self, element: &Element) -> Result<f64, EvalError> {
let res = match *element {
Element::Number(n) => n,
Element::Variable(name) => *self.variables.get(name).ok_or_else(
#[cold]
|| EvalError(name.to_owned()),
)?,
Element::UnOp(ref unop) => {
let operand = self.eval_element(&unop.operand)?;
#[allow(clippy::unreachable)]
match unop.op {
Operator::Plus => operand,
Operator::Minus => -operand,
Operator::Factorial => factorial(operand),
Operator::Times
| Operator::Divide
| Operator::Power
| Operator::Modulo => unreachable!(),
}
},
Element::BinOp(ref binop) => {
let left = self.eval_element(&binop.lhs)?;
let right = self.eval_element(&binop.rhs)?;
#[allow(clippy::unreachable)]
match binop.op {
Operator::Plus => left + right,
Operator::Minus => left - right,
Operator::Times => left * right,
Operator::Divide => left / right,
Operator::Power => left.powf(right),
Operator::Modulo => left % right,
Operator::Factorial => unreachable!(),
}
},
Element::Function(ref func) => {
let args = func
.args
.iter()
.map(|arg| self.eval_element(arg))
.collect::<Result<Vec<_>, EvalError>>()?;
func.call(&args)
},
};
Ok(res)
}
/// Evaluates an element within an expression without checking for errors.
fn eval_element_unchecked(&self, element: &Element) -> f64 {
match *element {
Element::Number(n) => n,
#[allow(clippy::unwrap_used)]
Element::Variable(name) => *self.variables.get(name).unwrap(),
Element::UnOp(ref unop) => {
let operand = self.eval_element_unchecked(&unop.operand);
#[allow(clippy::unreachable)]
match unop.op {
Operator::Plus => operand,
Operator::Minus => -operand,
Operator::Factorial => factorial(operand),
Operator::Times
| Operator::Divide
| Operator::Power
| Operator::Modulo => unreachable!(),
}
},
Element::BinOp(ref binop) => {
let left = self.eval_element_unchecked(&binop.lhs);
let right = self.eval_element_unchecked(&binop.rhs);
#[allow(clippy::unreachable)]
match binop.op {
Operator::Plus => left + right,
Operator::Minus => left - right,
Operator::Times => left * right,
Operator::Divide => left / right,
Operator::Power => left.powf(right),
Operator::Modulo => left % right,
Operator::Factorial => unreachable!(),
}
},
Element::Function(ref func) => {
let args = func
.args
.iter()
.map(|arg| self.eval_element_unchecked(arg))
.collect::<Vec<_>>();
func.call(&args)
},
}
}
}
/// Represents an error that occurs during expression evaluation, indicating that a variable was not provided.
#[derive(
Debug, Eq, PartialEq, thiserror::Error, Clone, Hash, Ord, PartialOrd,
)]
#[error("Evaluation error: '{0}' was not provided")]
pub struct EvalError(String);
//////////////////////////////////////////////////////////////////////////////
// TODO: replace this with variadic generics when it's available & stable //
//////////////////////////////////////////////////////////////////////////////
#[allow(clippy::too_many_arguments)]
#[rustfmt::skip]
impl<'a> Xprs<'a> {
/// Creates a function of one variable based on this [`Xprs`] instance.
///
/// # Errors
///
/// A [`BindError`] is returned if one or more required variables were not provided.
///
/// # Example
///
/// ```
/// use xprs::Parser;
///
/// let expression = Parser::default().parse("x + 2")?;
/// let func = expression.bind("x");
///
/// assert!(func.is_ok());
/// let func = func?;
///
/// let result = func(3.0);
/// assert_eq!(result, 5.0);
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[inline]
pub fn bind(self, var: &'a str) -> Result<impl Fn(f64) -> f64 + 'a, BindError> {
let variables: HashSet<&str> = HashSet::from([var]);
let missing_vars = self.vars.difference(&variables);
if let Some(bind_error) = BindError::from_diff(missing_vars) {
yeet!(bind_error);
}
Ok(move |val| self.eval_unchecked(&[(var, val)].into()))
}
/// Creates a function of two [`f64`] based on this [`Xprs`] instance.
///
/// # Errors
///
/// A [`BindError`] is returned if one or more required variables were not provided.
///
/// # Example
///
/// ```
/// use xprs::Parser;
///
/// let expression = Parser::default().parse("x + y")?;
/// let func = expression.bind2("x", "y");
///
/// assert!(func.is_ok());
/// let func = func?;
///
/// let result = func(3.0, 2.0);
/// assert_eq!(result, 5.0);
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[inline]
pub fn bind2(self, var1: &'a str, var2: &'a str) -> Result<impl Fn(f64, f64) -> f64 + 'a, BindError> {
let variables: HashSet<&str> = HashSet::from([var1, var2]);
let missing_vars = self.vars.difference(&variables);
if let Some(bind_error) = BindError::from_diff(missing_vars) {
yeet!(bind_error);
}
Ok(move |val1, val2| self.eval_unchecked(&[(var1, val1), (var2, val2)].into()))
}
/// Creates a function of three [`f64`] based on this [`Xprs`] instance.
///
/// # Errors
///
/// A [`BindError`] is returned if one or more required variables were not provided.
///
/// # Example
///
/// ```
/// use xprs::Parser;
///
/// let expression = Parser::default().parse("x + y + z")?;
/// let func = expression.bind3("x", "y", "z");
///
/// assert!(func.is_ok());
/// let func = func?;
///
/// let result = func(3.0, 2.0, 1.0);
/// assert_eq!(result, 6.0);
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[inline]
pub fn bind3(self, var1: &'a str, var2: &'a str, var3: &'a str) -> Result<impl Fn(f64, f64, f64) -> f64 + 'a, BindError> {
let variables: HashSet<&str> = HashSet::from([var1, var2, var3]);
let missing_vars = self.vars.difference(&variables);
if let Some(bind_error) = BindError::from_diff(missing_vars) {
yeet!(bind_error);
}
Ok(move |val1, val2, val3| self.eval_unchecked(&[(var1, val1), (var2, val2), (var3, val3)].into()))
}
/// Creates a function of four [`f64`] based on this [`Xprs`] instance.
///
/// # Errors
///
/// A [`BindError`] is returned if one or more required variables were not provided.
///
/// # Example
///
/// ```
/// use xprs::Parser;
///
/// let expression = Parser::default().parse("w + x + y + z")?;
/// let func = expression.bind4("w", "x", "y", "z");
///
/// assert!(func.is_ok());
/// let func = func?;
///
/// let result = func(1.0, 2.0, 3.0, 4.0);
/// assert_eq!(result, 10.0);
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[inline]
pub fn bind4(self, var1: &'a str, var2: &'a str, var3: &'a str, var4: &'a str) -> Result<impl Fn(f64, f64, f64, f64) -> f64 + 'a, BindError> {
let variables: HashSet<&str> = HashSet::from([var1, var2, var3, var4]);
let missing_vars = self.vars.difference(&variables);
if let Some(bind_error) = BindError::from_diff(missing_vars) {
yeet!(bind_error);
}
Ok(move |val1, val2, val3, val4| self.eval_unchecked(&[(var1, val1), (var2, val2), (var3, val3), (var4, val4)].into()))
}
/// Creates a function of five [`f64`] based on this [`Xprs`] instance.
///
/// # Errors
///
/// A [`BindError`] is returned if one or more required variables were not provided.
///
/// # Example
///
/// ```
/// use xprs::Parser;
///
/// let expression = Parser::default().parse("v + w + x + y + z")?;
/// let func = expression.bind5("v", "w", "x", "y", "z");
///
/// assert!(func.is_ok());
/// let func = func?;
///
/// let result = func(1.0, 2.0, 3.0, 4.0, 5.0);
/// assert_eq!(result, 15.0);
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[inline]
pub fn bind5(self, var1: &'a str, var2: &'a str, var3: &'a str, var4: &'a str, var5: &'a str) -> Result<impl Fn(f64, f64, f64, f64, f64) -> f64 + 'a, BindError> {
let variables: HashSet<&str> = HashSet::from([var1, var2, var3, var4, var5]);
let missing_vars = self.vars.difference(&variables);
if let Some(bind_error) = BindError::from_diff(missing_vars) {
yeet!(bind_error);
}
Ok(move |val1, val2, val3, val4, val5| self.eval_unchecked(&[(var1, val1), (var2, val2), (var3, val3), (var4, val4), (var5, val5)].into()))
}
/// Creates a function of six [`f64`] based on this [`Xprs`] instance.
///
/// # Errors
///
/// A [`BindError`] is returned if one or more required variables were not provided.
///
/// # Example
///
/// ```
/// use xprs::Parser;
///
/// let expression = Parser::default().parse("u + v + w + x + y + z")?;
/// let func = expression.bind6("u", "v", "w", "x", "y", "z");
///
/// assert!(func.is_ok());
/// let func = func?;
///
/// let result = func(1.0, 2.0, 3.0, 4.0, 5.0, 6.0);
/// assert_eq!(result, 21.0);
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[inline]
pub fn bind6(self, var1: &'a str, var2: &'a str, var3: &'a str, var4: &'a str, var5: &'a str, var6: &'a str) -> Result<impl Fn(f64, f64, f64, f64, f64, f64) -> f64 + 'a, BindError> {
let variables: HashSet<&str> = HashSet::from([var1, var2, var3, var4, var5, var6]);
let missing_vars = self.vars.difference(&variables);
if let Some(bind_error) = BindError::from_diff(missing_vars) {
yeet!(bind_error);
}
Ok(move |val1, val2, val3, val4, val5, val6| self.eval_unchecked(&[(var1, val1), (var2, val2), (var3, val3), (var4, val4), (var5, val5), (var6, val6)].into()))
}
/// Creates a function of seven [`f64`] based on this [`Xprs`] instance.
///
/// # Errors
///
/// A [`BindError`] is returned if one or more required variables were not provided.
///
/// # Example
///
/// ```
/// use xprs::Parser;
///
/// let expression = Parser::default().parse("t + u + v + w + x + y + z")?;
/// let func = expression.bind7("t", "u", "v", "w", "x", "y", "z");
///
/// assert!(func.is_ok());
/// let func = func?;
///
/// let result = func(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0);
/// assert_eq!(result, 28.0);
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[inline]
pub fn bind7(self, var1: &'a str, var2: &'a str, var3: &'a str, var4: &'a str, var5: &'a str, var6: &'a str, var7: &'a str) -> Result<impl Fn(f64, f64, f64, f64, f64, f64, f64) -> f64 + 'a, BindError> {
let variables: HashSet<&str> = HashSet::from([var1, var2, var3, var4, var5, var6, var7]);
let missing_vars = self.vars.difference(&variables);
if let Some(bind_error) = BindError::from_diff(missing_vars) {
yeet!(bind_error);
}
Ok(move |val1, val2, val3, val4, val5, val6, val7| self.eval_unchecked(&[(var1, val1), (var2, val2), (var3, val3), (var4, val4), (var5, val5), (var6, val6), (var7, val7)].into()))
}
/// Creates a function of eight [`f64`] based on this [`Xprs`] instance.
///
/// # Errors
///
/// A [`BindError`] is returned if one or more required variables were not provided.
///
/// # Example
///
/// ```
/// use xprs::Parser;
///
/// let expression = Parser::default().parse("s + t + u + v + w + x + y + z")?;
/// let func = expression.bind8("s", "t", "u", "v", "w", "x", "y", "z");
///
/// assert!(func.is_ok());
/// let func = func?;
///
/// let result = func(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0);
/// assert_eq!(result, 36.0);
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[inline]
pub fn bind8(self, var1: &'a str, var2: &'a str, var3: &'a str, var4: &'a str, var5: &'a str, var6: &'a str, var7: &'a str, var8: &'a str) -> Result<impl Fn(f64, f64, f64, f64, f64, f64, f64, f64) -> f64 + 'a, BindError> {
let variables: HashSet<&str> = HashSet::from([var1, var2, var3, var4, var5, var6, var7, var8]);
let missing_vars = self.vars.difference(&variables);
if let Some(bind_error) = BindError::from_diff(missing_vars) {
yeet!(bind_error);
}
Ok(move |val1, val2, val3, val4, val5, val6, val7, val8| self.eval_unchecked(&[(var1, val1), (var2, val2), (var3, val3), (var4, val4), (var5, val5), (var6, val6), (var7, val7), (var8, val8)].into()))
}
/// Creates a function of nine [`f64`] based on this [`Xprs`] instance.
///
/// # Errors
///
/// A [`BindError`] is returned if one or more required variables were not provided.
///
/// # Example
///
/// ```
/// use xprs::Parser;
///
/// let expression = Parser::default().parse("r + s + t + u + v + w + x + y + z")?;
/// let func = expression.bind9("r", "s", "t", "u", "v", "w", "x", "y", "z");
///
/// assert!(func.is_ok());
/// let func = func?;
///
/// let result = func(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0);
/// assert_eq!(result, 45.0);
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[inline]
pub fn bind9(self, var1: &'a str, var2: &'a str, var3: &'a str, var4: &'a str, var5: &'a str, var6: &'a str, var7: &'a str, var8: &'a str, var9: &'a str) -> Result<impl Fn(f64, f64, f64, f64, f64, f64, f64, f64, f64) -> f64 + 'a, BindError> {
let variables: HashSet<&str> = HashSet::from([var1, var2, var3, var4, var5, var6, var7, var8, var9]);
let missing_vars = self.vars.difference(&variables);
if let Some(bind_error) = BindError::from_diff(missing_vars) {
yeet!(bind_error);
}
Ok(move |val1, val2, val3, val4, val5, val6, val7, val8, val9| self.eval_unchecked(&[(var1, val1), (var2, val2), (var3, val3), (var4, val4), (var5, val5), (var6, val6), (var7, val7), (var8, val8), (var9, val9)].into()))
}
// NOTE: Too lazy to implement this for more than 9 variables even with Copilot
// + I don't really think anyone will need more than 9 variables anyway
/// Creates a function of any number* of [`f64`] based on this [`Xprs`] instance.
/// *The number of variables must be known at compile time.
///
/// The returned closure takes an array of [`f64`] as input and returns an [`f64`].
///
/// # Errors
///
/// A [`BindError`] is returned if one or more required variables were not provided.
///
/// # Example
///
/// ```
/// use xprs::Parser;
///
/// let expression = Parser::default().parse("a + b + c + d")?;
/// let func = expression.bind_n(["a", "b", "c", "d"]);
///
/// assert!(func.is_ok());
/// let func = func?;
///
/// let result = func([1.0, 2.0, 3.0, 4.0]);
/// assert_eq!(result, 10.0);
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[inline]
pub fn bind_n<const T: usize>(self, vars: [&'a str; T]) -> Result<impl Fn([f64; T]) -> f64 + 'a, BindError> {
let variables: HashSet<&str> = HashSet::from(vars);
let missing_vars = self.vars.difference(&variables);
if let Some(bind_error) = BindError::from_diff(missing_vars) {
yeet!(bind_error);
}
Ok(move |values| self.eval_unchecked(&vars.into_iter().zip(values).collect()))
}
/// Creates a function of any number of [`f64`] based on this [`Xprs`] instance.
///
/// The returned closure takes a slice of [`f64`] as input and
/// returns a [`Result`] containing an [`f64`] if the evaluation is successful, or an [`EvalError`] if an error occurs.
///
/// # Errors
///
/// A [`BindError`] is returned if one or more required variables were not provided.
///
/// # Example
///
/// ```
/// use xprs::Parser;
///
/// let expression = Parser::default().parse("a + b + c + d")?;
/// let func = expression.bind_n_runtime(&["a", "b", "c", "d"]);
///
/// assert!(func.is_ok());
/// let func = func?;
///
/// let result = func(&[1.0, 2.0, 3.0, 4.0])?;
/// assert_eq!(result, 10.0);
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[inline]
pub fn bind_n_runtime(self, vars: &'a [&'a str]) -> Result<impl Fn(&[f64]) -> Result<f64, EvalError> + 'a, BindError> {
let variables: HashSet<&str> = vars.iter().copied().collect();
let missing_vars = self.vars.difference(&variables);
if let Some(bind_error) = BindError::from_diff(missing_vars) {
yeet!(bind_error);
}
// can't drop the closure from returning a result because we can't use the unchecked version
// because we don't know the length of the slice at compile time
// it could be different from the length of the slice of variables names
Ok(move |values: &[f64]| self.eval(&vars.iter().copied().zip(values.iter().copied()).collect()))
}
}
/// Represents errors that occur when binding variables for expression evaluation.
#[derive(
Debug, Eq, PartialEq, thiserror::Error, Clone, Hash, Ord, PartialOrd,
)]
#[non_exhaustive]
pub enum BindError {
#[error("Variable '{0}' was not provided")]
OneVariable(String),
#[error("Variables '{0}' were not provided")]
MultipleVariables(String),
}
use std::collections::{hash_map::RandomState, hash_set::Difference};
impl BindError {
/// Converts a [`Difference`] iterator of missing variables into a [`BindError`].
fn from_diff(
missing_vars: Difference<'_, &str, RandomState>,
) -> Option<Self> {
let mut peekable = missing_vars.peekable();
let mut count: u8 = 0;
let mut missing_vars_str = String::new();
while let Some(missing_var) = peekable.next() {
count += 1;
missing_vars_str.push_str(missing_var);
if peekable.peek().is_some() {
missing_vars_str.push_str(", ");
}
}
match count {
0 => None,
1 => Some(Self::OneVariable(missing_vars_str)),
_ => Some(Self::MultipleVariables(missing_vars_str)),
}
}
}