lambdust 0.1.1

A Scheme dialect with gradual typing and effect systems
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
//! Rational number implementation with optimized arithmetic
//!
//! Provides exact rational arithmetic using GCD-based reduction and
//! optimized algorithms for common operations.

use std::cmp::Ordering;
use std::fmt;
use std::hash::{Hash, Hasher};
use std::ops::{Add, Sub, Mul, Div, Neg};

/// Exact rational number representation
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Rational {
    /// Numerator of the rational number
    pub numerator: i64,
    /// Denominator of the rational number (never zero)
    pub denominator: i64,
}

impl Rational {
    /// Creates a new rational number with automatic reduction
    pub fn new(numerator: i64, denominator: i64) -> Self {
        if denominator == 0 {
            panic!("Rational number cannot have zero denominator");
        }

        if numerator == 0 {
            return Self {
                numerator: 0,
                denominator: 1,
            };
        }

        // Reduce the fraction using GCD
        let gcd = gcd(numerator.unsigned_abs(), denominator.unsigned_abs()) as i64;
        let mut num = numerator / gcd;
        let mut den = denominator / gcd;

        // Ensure denominator is positive
        if den < 0 {
            num = -num;
            den = -den;
        }

        Self {
            numerator: num,
            denominator: den,
        }
    }

    /// Creates a rational from an integer
    pub fn from_integer(n: i64) -> Self {
        Self {
            numerator: n,
            denominator: 1,
        }
    }

    /// Zero rational number
    pub const ZERO: Self = Self {
        numerator: 0,
        denominator: 1,
    };

    /// One rational number
    pub const ONE: Self = Self {
        numerator: 1,
        denominator: 1,
    };

    /// Negative one rational number
    pub const NEG_ONE: Self = Self {
        numerator: -1,
        denominator: 1,
    };

    /// Half rational number
    pub const HALF: Self = Self {
        numerator: 1,
        denominator: 2,
    };

    /// Checks if this rational is zero
    pub fn is_zero(&self) -> bool {
        self.numerator == 0
    }

    /// Checks if this rational is positive
    pub fn is_positive(&self) -> bool {
        self.numerator > 0
    }

    /// Checks if this rational is negative
    pub fn is_negative(&self) -> bool {
        self.numerator < 0
    }

    /// Checks if this rational is an integer
    pub fn is_integer(&self) -> bool {
        self.denominator == 1
    }

    /// Returns the absolute value
    pub fn abs(&self) -> Self {
        Self {
            numerator: self.numerator.abs(),
            denominator: self.denominator,
        }
    }

    /// Returns the reciprocal
    pub fn reciprocal(&self) -> Self {
        if self.numerator == 0 {
            panic!("Cannot compute reciprocal of zero");
        }
        Self::new(self.denominator, self.numerator)
    }

    /// Converts to floating point (with potential precision loss)
    pub fn to_f64(&self) -> f64 {
        self.numerator as f64 / self.denominator as f64
    }

    /// Converts to integer if possible (exact integers only)
    pub fn to_i64(&self) -> Option<i64> {
        if self.denominator == 1 {
            Some(self.numerator)
        } else {
            None
        }
    }

    /// Raises this rational to an integer power
    pub fn powi(&self, exponent: i32) -> Self {
        if exponent == 0 {
            Self::ONE
        } else if exponent > 0 {
            Self {
                numerator: self.numerator.pow(exponent as u32),
                denominator: self.denominator.pow(exponent as u32),
            }
        } else {
            let abs_exp = (-exponent) as u32;
            Self {
                numerator: self.denominator.pow(abs_exp),
                denominator: self.numerator.pow(abs_exp),
            }
        }
    }

    /// Returns the floor of this rational
    pub fn floor(&self) -> i64 {
        if self.numerator >= 0 {
            self.numerator / self.denominator
        } else {
            (self.numerator - self.denominator + 1) / self.denominator
        }
    }

    /// Returns the ceiling of this rational
    pub fn ceil(&self) -> i64 {
        if self.numerator >= 0 {
            (self.numerator + self.denominator - 1) / self.denominator
        } else {
            self.numerator / self.denominator
        }
    }

    /// Returns the truncated value (towards zero)
    pub fn trunc(&self) -> i64 {
        self.numerator / self.denominator
    }

    /// Returns the fractional part
    pub fn fract(&self) -> Self {
        let integer_part = self.trunc();
        *self - Self::from_integer(integer_part)
    }

    /// Continued fraction representation (partial)
    pub fn to_continued_fraction(&self, max_terms: usize) -> Vec<i64> {
        let mut result = Vec::new();
        let mut num = self.numerator;
        let mut den = self.denominator;

        for _ in 0..max_terms {
            if den == 0 {
                break;
            }

            let quotient = num / den;
            result.push(quotient);

            let remainder = num % den;
            num = den;
            den = remainder;
        }

        result
    }

    /// Creates a rational from a continued fraction
    pub fn from_continued_fraction(terms: &[i64]) -> Self {
        if terms.is_empty() {
            return Self::ZERO;
        }

        let mut result = Self::from_integer(terms[terms.len() - 1]);

        for &term in terms.iter().rev().skip(1) {
            result = result.reciprocal() + Self::from_integer(term);
        }

        result
    }

    /// Mediant of two rationals (used in Farey sequences)
    pub fn mediant(&self, other: &Self) -> Self {
        Self::new(
            self.numerator + other.numerator,
            self.denominator + other.denominator,
        )
    }
}

impl Add for Rational {
    type Output = Self;

    fn add(self, other: Self) -> Self {
        // a/b + c/d = (ad + bc) / (bd)
        let numerator = self.numerator * other.denominator + other.numerator * self.denominator;
        let denominator = self.denominator * other.denominator;
        Self::new(numerator, denominator)
    }
}

impl Sub for Rational {
    type Output = Self;

    fn sub(self, other: Self) -> Self {
        // a/b - c/d = (ad - bc) / (bd)
        let numerator = self.numerator * other.denominator - other.numerator * self.denominator;
        let denominator = self.denominator * other.denominator;
        Self::new(numerator, denominator)
    }
}

impl Mul for Rational {
    type Output = Self;

    fn mul(self, other: Self) -> Self {
        // (a/b) * (c/d) = (ac) / (bd)
        Self::new(
            self.numerator * other.numerator,
            self.denominator * other.denominator,
        )
    }
}

impl Div for Rational {
    type Output = Self;

    fn div(self, other: Self) -> Self {
        if other.is_zero() {
            panic!("Division by zero");
        }
        // (a/b) / (c/d) = (a/b) * (d/c) = (ad) / (bc)
        Self::new(
            self.numerator * other.denominator,
            self.denominator * other.numerator,
        )
    }
}

impl Neg for Rational {
    type Output = Self;

    fn neg(self) -> Self {
        Self {
            numerator: -self.numerator,
            denominator: self.denominator,
        }
    }
}

// Operations with integers

impl Add<i64> for Rational {
    type Output = Self;

    fn add(self, other: i64) -> Self {
        self + Self::from_integer(other)
    }
}

impl Sub<i64> for Rational {
    type Output = Self;

    fn sub(self, other: i64) -> Self {
        self - Self::from_integer(other)
    }
}

impl Mul<i64> for Rational {
    type Output = Self;

    fn mul(self, other: i64) -> Self {
        Self::new(self.numerator * other, self.denominator)
    }
}

impl Div<i64> for Rational {
    type Output = Self;

    fn div(self, other: i64) -> Self {
        if other == 0 {
            panic!("Division by zero");
        }
        Self::new(self.numerator, self.denominator * other)
    }
}

impl PartialOrd for Rational {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for Rational {
    fn cmp(&self, other: &Self) -> Ordering {
        // Compare a/b with c/d by comparing ad with bc
        let left = self.numerator * other.denominator;
        let right = other.numerator * self.denominator;
        left.cmp(&right)
    }
}

impl fmt::Display for Rational {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if self.denominator == 1 {
            write!(f, "{}", self.numerator)
        } else {
            write!(f, "{}/{}", self.numerator, self.denominator)
        }
    }
}

impl Hash for Rational {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.numerator.hash(state);
        self.denominator.hash(state);
    }
}

/// Computes the greatest common divisor using Euclid's algorithm
pub fn gcd(a: u64, b: u64) -> u64 {
    if b == 0 {
        a
    } else {
        gcd(b, a % b)
    }
}

/// Computes the least common multiple
pub fn lcm(a: u64, b: u64) -> u64 {
    if a == 0 && b == 0 {
        0
    } else {
        (a / gcd(a, b)) * b
    }
}

/// Extended Euclidean algorithm
/// Returns (gcd, x, y) such that ax + by = gcd
pub fn extended_gcd(a: i64, b: i64) -> (i64, i64, i64) {
    if b == 0 {
        (a, 1, 0)
    } else {
        let (g, x, y) = extended_gcd(b, a % b);
        (g, y, x - (a / b) * y)
    }
}

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

    #[test]
    fn test_rational_creation() {
        let r1 = Rational::new(3, 4);
        assert_eq!(r1.numerator, 3);
        assert_eq!(r1.denominator, 4);

        let r2 = Rational::new(6, 8);
        assert_eq!(r2.numerator, 3);
        assert_eq!(r2.denominator, 4);

        let r3 = Rational::new(-3, 4);
        assert_eq!(r3.numerator, -3);
        assert_eq!(r3.denominator, 4);

        let r4 = Rational::new(3, -4);
        assert_eq!(r4.numerator, -3);
        assert_eq!(r4.denominator, 4);
    }

    #[test]
    fn test_rational_arithmetic() {
        let r1 = Rational::new(1, 2);
        let r2 = Rational::new(1, 3);

        let sum = r1 + r2;
        assert_eq!(sum, Rational::new(5, 6));

        let diff = r1 - r2;
        assert_eq!(diff, Rational::new(1, 6));

        let prod = r1 * r2;
        assert_eq!(prod, Rational::new(1, 6));

        let quot = r1 / r2;
        assert_eq!(quot, Rational::new(3, 2));
    }

    #[test]
    fn test_rational_comparison() {
        let r1 = Rational::new(1, 2);
        let r2 = Rational::new(2, 4);
        let r3 = Rational::new(1, 3);

        assert_eq!(r1, r2);
        assert!(r1 > r3);
        assert!(r3 < r1);
    }

    #[test]
    fn test_rational_power() {
        let r = Rational::new(2, 3);
        let r_squared = r.powi(2);
        assert_eq!(r_squared, Rational::new(4, 9));

        let r_inv = r.powi(-1);
        assert_eq!(r_inv, Rational::new(3, 2));
    }

    #[test]
    fn test_continued_fraction() {
        let r = Rational::new(22, 7); // Approximation of π
        let cf = r.to_continued_fraction(10);
        assert_eq!(cf, vec![3, 7]);

        let reconstructed = Rational::from_continued_fraction(&cf);
        assert_eq!(reconstructed, r);
    }

    #[test]
    fn test_rational_display() {
        assert_eq!(format!("{}", Rational::new(3, 4)), "3/4");
        assert_eq!(format!("{}", Rational::new(5, 1)), "5");
        assert_eq!(format!("{}", Rational::new(-3, 4)), "-3/4");
        assert_eq!(format!("{}", Rational::new(0, 1)), "0");
    }

    #[test]
    fn test_gcd() {
        assert_eq!(gcd(48, 18), 6);
        assert_eq!(gcd(17, 13), 1);
        assert_eq!(gcd(0, 5), 5);
        assert_eq!(gcd(5, 0), 5);
    }

    #[test]
    fn test_lcm() {
        assert_eq!(lcm(4, 6), 12);
        assert_eq!(lcm(17, 13), 221);
        assert_eq!(lcm(0, 5), 0);
    }

    #[test]
    fn test_extended_gcd() {
        let (g, x, y) = extended_gcd(240, 46);
        assert_eq!(g, 2);
        assert_eq!(240 * x + 46 * y, g);
    }
}