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
//! An implementation of a fixed-size iterator over the rational numbers based on the
//! algorithm described by Gibbons, Lester, and Bird in
//! [Functional Pearl: Enumerating the Rationals].
//!
//! [Functional Pearl: Enumerating the Rationals]: http://www.cs.ox.ac.uk/people/jeremy.gibbons/publications/rationals.pdf

#![cfg_attr(not(test), no_std)]

use num_integer::Integer;
use num_rational::Ratio;
use num_traits::cast::FromPrimitive;

pub struct Rationals<T: Integer> {
    state: Ratio<T>,
}

impl<T> Rationals<T>
where
    T: Integer + FromPrimitive + Clone,
{
    /// Create a new iterator over the rationals.
    ///
    /// ```
    /// use iter_rationals::Rationals;
    ///
    /// let rationals = Rationals::<u32>::new();
    ///
    /// for r in rationals.take(10) {
    ///     println!("{}", r);
    /// }
    /// ```
    pub fn new() -> Self {
        Self { state: Self::one() }
    }

    fn one() -> Ratio<T> {
        Ratio::from_integer(T::from_u64(1).unwrap())
    }
}

impl<T> Default for Rationals<T>
where
    T: Integer + FromPrimitive + Clone,
{
    fn default() -> Self {
        Self::new()
    }
}

impl<T> Iterator for Rationals<T>
where
    T: Integer + Clone + core::ops::Add,
{
    type Item = Ratio<T>;

    fn next(&mut self) -> Option<Self::Item> {
        let r = self.state.clone();
        let n = r.trunc();
        let y = r.fract();
        let next = (n + T::one() - y).recip();
        self.state = next;
        Some(r)
    }
}

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

    #[test]
    fn test_speed_is_reasonable() {
        let mut r = Rationals::<u32>::new();
        let nth_rational = r.nth(1_000_000).unwrap();
        println!("{}", nth_rational);
        let expected = Ratio::new(1287, 1096);
        assert_eq!(expected, nth_rational);
    }

    #[test]
    fn test_first_values_are_as_expected() {
        let expected_parts = [
            (1, 1),
            (1, 2),
            (2, 1),
            (1, 3),
            (3, 2),
            (2, 3),
            (3, 1),
            (1, 4),
            (4, 3),
            (3, 5),
            (5, 2),
            (2, 5),
            (5, 3),
            (3, 4),
            (4, 1),
        ];
        let expected: Vec<Ratio<u32>> = expected_parts
            .iter()
            .map(|p| Ratio::new(p.0, p.1))
            .collect();
        let found: Vec<Ratio<u32>> = Rationals::<u32>::new().take(expected.len()).collect();
        assert_eq!(found, expected);
    }

    #[test]
    fn test_builtin_types() {
        let limit = 32;

        Rationals::<u8>::new().nth(limit).unwrap();
        Rationals::<u16>::new().nth(limit).unwrap();
        Rationals::<u32>::new().nth(limit).unwrap();
        Rationals::<u64>::new().nth(limit).unwrap();
        Rationals::<u128>::new().nth(limit).unwrap();

        Rationals::<i8>::new().nth(limit).unwrap();
        Rationals::<i16>::new().nth(limit).unwrap();
        Rationals::<i32>::new().nth(limit).unwrap();
        Rationals::<i64>::new().nth(limit).unwrap();
        Rationals::<i128>::new().nth(limit).unwrap();

        Rationals::<usize>::new().nth(limit).unwrap();
        Rationals::<isize>::new().nth(limit).unwrap();
    }
}