realistic 0.8.2

Towards an API for the Real Numbers
Documentation
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
use crate::{Problem, Rational, Real};
use std::collections::HashMap;
use std::iter::Peekable;
use std::str::Chars;

type Symbols = HashMap<String, Real>;

#[derive(Clone, Debug, PartialEq)]
enum Operator {
    Plus,
    Minus,
    Star,
    Slash,
    Sqrt,
    Exp,
    Log10,
    Ln,
    Cos,
    Sin,
    Tan,
    Pow,
}

#[derive(Clone, Debug, PartialEq)]
enum Operand {
    Literal(Rational),     // e.g. 123_456.789
    Symbol(String),        // e.g. "pi"
    SubExpression(Simple), // e.g. (+ 1 2 3)
}

impl Operand {
    pub fn value(&self, names: &Symbols) -> Result<Real, Problem> {
        match self {
            Operand::Literal(n) => Ok(Real::new(n.clone())),
            Operand::Symbol(s) => Simple::lookup(s, names),
            Operand::SubExpression(xpr) => xpr.evaluate(names),
        }
    }
}

#[derive(Clone, Debug, PartialEq)]
pub struct Simple {
    op: Operator,
    operands: Vec<Operand>,
}

fn parse_problem(problem: Problem) -> &'static str {
    use Problem::*;
    match problem {
        DivideByZero => "Attempting to divide by zero",
        NotFound => "Symbol not found",
        ParseError => "Unable to parse number",
        _ => {
            eprintln!("Specifically the problem is {problem:?}");
            "Some unknown problem during parsing"
        }
    }
}

impl Simple {
    fn lookup(name: &str, names: &Symbols) -> Result<Real, Problem> {
        if let Some(value) = names.get(name) {
            return Ok(value.clone());
        }
        match name {
            "pi" => Ok(Real::pi()),
            "e" => Ok(Real::e()),
            _ => Err(Problem::NotFound),
        }
    }

    pub fn evaluate(&self, names: &Symbols) -> Result<Real, Problem> {
        use Operator::*;
        match self.op {
            Plus => {
                let mut value = Real::zero();
                for operand in &self.operands {
                    value = value + operand.value(names)?;
                }
                Ok(value)
            }
            Minus => match self.operands.len() {
                0 => Err(Problem::InsufficientParameters),
                1 => {
                    let operand = self.operands.first().unwrap();
                    let value = -(operand.value(names)?);
                    Ok(value)
                }
                _ => {
                    let mut value: Real = self.operands.first().unwrap().value(names)?;
                    let operands = self.operands.iter().skip(1);
                    for operand in operands {
                        value = value - (operand.value(names)?);
                    }
                    Ok(value)
                }
            },
            Star => {
                let mut value = Real::new(Rational::one());
                for operand in &self.operands {
                    value = value * operand.value(names)?;
                }
                Ok(value)
            }
            Slash => match self.operands.len() {
                0 => Err(Problem::InsufficientParameters),
                1 => {
                    let operand = self.operands.first().unwrap();
                    operand.value(names)?.inverse()
                }
                _ => {
                    let mut value: Real = self.operands.first().unwrap().value(names)?;
                    let operands = self.operands.iter().skip(1);
                    for operand in operands {
                        value = (value / operand.value(names)?)?;
                    }
                    Ok(value)
                }
            },
            Exp => {
                if self.operands.len() != 1 {
                    return Err(Problem::ParseError);
                }
                let operand = self.operands.first().unwrap();
                let value = operand.value(names)?.exp()?;
                Ok(value)
            }
            Log10 => {
                if self.operands.len() != 1 {
                    return Err(Problem::ParseError);
                }
                let operand = self.operands.first().unwrap();
                let value = operand.value(names)?.log10()?;
                Ok(value)
            }
            Ln => {
                if self.operands.len() != 1 {
                    return Err(Problem::ParseError);
                }
                let operand = self.operands.first().unwrap();
                let value = operand.value(names)?.ln()?;
                Ok(value)
            }
            Sqrt => {
                if self.operands.len() != 1 {
                    return Err(Problem::ParseError);
                }
                let operand = self.operands.first().unwrap();
                let value = operand.value(names)?.sqrt()?;
                Ok(value)
            }
            Cos => {
                if self.operands.len() != 1 {
                    return Err(Problem::ParseError);
                }
                let operand = self.operands.first().unwrap();
                let value = operand.value(names)?.cos();
                Ok(value)
            }
            Sin => {
                if self.operands.len() != 1 {
                    return Err(Problem::ParseError);
                }
                let operand = self.operands.first().unwrap();
                let value = operand.value(names)?.sin();
                Ok(value)
            }
            Tan => {
                if self.operands.len() != 1 {
                    return Err(Problem::ParseError);
                }
                let operand = self.operands.first().unwrap();
                let value = operand.value(names)?.tan()?;
                Ok(value)
            }
            Pow => {
                if self.operands.len() != 2 {
                    return Err(Problem::ParseError);
                }
                let op1 = &self.operands[0];
                let op2 = &self.operands[1];
                let v1 = op1.value(names)?;
                let v2 = op2.value(names)?;
                let value = v1.pow(v2)?;
                Ok(value)
            }
        }
    }

    fn operator(chars: &mut Peekable<Chars>) -> Result<Operator, &'static str> {
        let mut op = String::new();

        while let Some(c) = chars.peek() {
            match c {
                'A'..='Z' | 'a'..='z' => op.push(*c),
                _ => break,
            }
            chars.next();
        }
        op.make_ascii_lowercase();

        use Operator::*;
        match op.as_str() {
            "log" | "log10" => Ok(Log10),
            "ln" | "l" => Ok(Ln),
            "exp" | "e" => Ok(Exp),
            "sqrt" | "s" => Ok(Sqrt),
            "cos" => Ok(Cos),
            "sin" => Ok(Sin),
            "pow" => Ok(Pow),
            "tan" => Ok(Tan),
            _ => Err("No such operator"),
        }
    }

    pub fn parse(chars: &mut Peekable<Chars>) -> Result<Self, &'static str> {
        if let Some('(') = chars.peek() {
            chars.next();
        } else {
            return Err("No parenthetical expression");
        }

        use Operator::*;
        // One operator
        let op: Operator = match chars.peek() {
            Some('+') => {
                chars.next();
                Plus
            }
            Some('-') => {
                chars.next();
                Minus
            }
            Some('*') => {
                chars.next();
                Star
            }
            Some('/') => {
                chars.next();
                Slash
            }
            Some('^') => {
                chars.next();
                Pow
            }
            Some('') => {
                chars.next();
                Sqrt
            }
            Some('a'..='z') => Self::operator(chars)?,
            _ => return Err("Unexpected symbol while looking for an operator"),
        };

        // One whitespace character
        match chars.peek() {
            Some(' ' | '\t') => {
                chars.next();
            }
            _ => return Err("No whitespace after operator"),
        }

        let mut operands: Vec<Operand> = Vec::new();

        // Operands
        while let Some(c) = chars.peek() {
            match c {
                ' ' | '\t' => {
                    // ignore
                    chars.next();
                }
                '#' | 'a'..='z' => {
                    let operand = Self::consume_symbol(chars);
                    operands.push(operand);
                }
                '-' | '0'..='9' => {
                    let operand = Self::consume_literal(chars).map_err(parse_problem)?;
                    operands.push(operand);
                }
                '(' => {
                    let xpr = Self::parse(chars)?;
                    operands.push(Operand::SubExpression(xpr));
                }
                ')' => {
                    chars.next();
                    return Ok(Simple { op, operands });
                }
                _ => return Err("Unexpected character while looking for operands ..."),
            }
        }

        Err("Incomplete expression")
    }

    // Consume a symbol, starting with # or a letter and consisting of zero or more:
    // letters, underscores or digits
    fn consume_symbol(c: &mut Peekable<Chars>) -> Operand {
        let mut sym = String::new();

        if let Some('#') = c.peek() {
            sym.push('#');
            c.next();
        }
        while let Some(item) = c.peek() {
            match item {
                'A'..='Z' | 'a'..='z' | '0'..='9' => sym.push(*item),
                _ => break,
            }
            c.next();
        }

        Operand::Symbol(sym)
    }

    // Consume a literal, for now presumably a single number consisting of:
    // a possible leading minus symbol, then
    // digits, the decimal point or a slash and optionally commas, underscores etc. which are ignored
    fn consume_literal(c: &mut Peekable<Chars>) -> Result<Operand, Problem> {
        let mut num = String::new();

        if let Some('-') = c.peek() {
            num.push('-');
            c.next();
        }
        while let Some(item) = c.peek() {
            match item {
                '0'..='9' | '.' | '/' => num.push(*item),
                '_' | ',' | '\'' => { /* ignore */ }
                _ => break,
            }
            c.next();
        }

        let n: Rational = num.parse()?;

        Ok(Operand::Literal(n))
    }
}

impl std::str::FromStr for Simple {
    type Err = &'static str;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let mut chars = s.chars().peekable();
        Simple::parse(&mut chars)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn missing_close() {
        let xpr: Result<Simple, &str> = "(+ (* (e 4) (e 6))".parse();
        assert_eq!(xpr, Err("Incomplete expression"))
    }

    #[test]
    fn two() {
        let empty = HashMap::new();
        let xpr: Simple = "(* 1/3 15/4 1.6)".parse().unwrap();
        let result = xpr.evaluate(&empty).unwrap();
        let ans = format!("{result}");
        assert_eq!(ans, "2");
    }

    #[test]
    fn division_zero() {
        let empty = HashMap::new();
        let xpr: Simple = "(/ 0)".parse().unwrap();
        let result = xpr.evaluate(&empty);
        assert_eq!(result, Err(Problem::DivideByZero))
    }

    #[test]
    fn simple_arithmetic() {
        let empty = HashMap::new();
        let xpr: Simple = "(+ 1 (* 2 3) 4)".parse().unwrap();
        let result = xpr.evaluate(&empty).unwrap();
        assert!(result.is_integer());
        let ans = format!("{result}");
        assert_eq!(ans, "11");
    }

    #[test]
    fn fractions() {
        let empty = HashMap::new();
        let xpr: Simple = "(/ (+ 1 2) (* 3 4))".parse().unwrap();
        let result = xpr.evaluate(&empty).unwrap();
        let ans = format!("{result}");
        assert_eq!(ans, "1/4");
        let decimal = format!("{result:e}");
        assert_eq!(decimal, "2.5e-1");
    }

    #[test]
    fn sqrts() {
        let empty = HashMap::new();
        let xpr: Simple = "(* (√ 40) (√ 90))".parse().unwrap();
        let result = xpr.evaluate(&empty).unwrap();
        let ans = format!("{result}");
        assert_eq!(ans, "60");
        let xpr: Simple = "(* (√ 14) (√ 1666350))".parse().unwrap();
        let result = xpr.evaluate(&empty).unwrap();
        let ans = format!("{result}");
        assert_eq!(ans, "4830");
    }

    #[test]
    fn sqrt_pi() {
        let empty = HashMap::new();
        let xpr: Simple = "(√ (+ pi pi pi pi))".parse().unwrap();
        let result = xpr.evaluate(&empty).unwrap();
        let ans = format!("{result:.32e}");
        assert_eq!(ans, "3.54490770181103205459633496668229e0");
    }

    #[test]
    fn pi() {
        let empty = HashMap::new();
        let xpr: Simple = "(* (+ pi pi) (* 3 pi))".parse().unwrap();
        let result = xpr.evaluate(&empty).unwrap();
        let ans = format!("{result:.32e}");
        assert_eq!(ans, "5.92176264065361517130069459992569e1");
    }

    #[test]
    fn pi_e_4() {
        let empty = HashMap::new();
        let xpr: Simple = "(* pi e 4)".parse().unwrap();
        let result = xpr.evaluate(&empty).unwrap();
        let ans = format!("{result:.32e}");
        assert_eq!(ans, "3.41589368906942682618542034781863e1");
    }

    #[test]
    fn ln_e() {
        let empty = HashMap::new();
        let xpr: Simple = "(l (* (e 4) (e 6)))".parse().unwrap();
        let result = xpr.evaluate(&empty).unwrap();
        assert!(result.is_integer());
        let ans = format!("{result}");
        assert_eq!(ans, "10");
    }

    #[test]
    fn div_pi_e_4() {
        let empty = HashMap::new();
        let xpr: Simple = "(/ pi e 4)".parse().unwrap();
        let result = xpr.evaluate(&empty).unwrap();
        let ans = format!("{result:.32e}");
        assert_eq!(ans, "2.88931837447730429477523295828174e-1");
    }

    #[test]
    fn e_minus_one() {
        let empty = HashMap::new();
        let xpr: Simple = "(/ e)".parse().unwrap();
        let result = xpr.evaluate(&empty).unwrap();
        let ans = format!("{result:.32e}");
        assert_eq!(ans, "3.67879441171442321595523770161461e-1");
    }

    #[test]
    fn precision() {
        let empty = HashMap::new();
        let xpr: Simple =
            "(* 35088.93592003040493454779969771102629 35088.93592003040493454779969771102629)"
                .parse()
                .unwrap();
        let result = xpr.evaluate(&empty).unwrap();
        let ans = format!("{result:#.29}");
        assert_eq!(ans, "1231233424.00000000000000000000000000032");
    }

    #[test]
    fn tan() {
        let empty = HashMap::new();
        let xpr: Simple = "(/ (* (tan (* pi 3.8)) 7.9) (tan (/ pi 5)))"
            .parse()
            .unwrap();
        let result = xpr.evaluate(&empty).unwrap();
        let m79: Real = "-7.9".parse().unwrap();
        assert_eq!(result, m79);
    }
}