adic 0.5.1

Arithmetic and rootfinding for p-adic 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
//! Map and compose [`Sequences`](Sequence)

use std::{
    cmp::PartialOrd,
    iter::repeat,
    ops::{Add, Mul, Sub},
};
use itertools::{EitherOrBoth, Itertools};
use crate::local_num::{LocalOne, LocalZero};
use super::Sequence;


#[derive(Debug, Clone)]
/// Enumerate a [`Sequence`]
pub struct EnumeratedSequence<S>
where S: Sequence {
    sequence: S,
}

impl<S> EnumeratedSequence<S>
where S: Sequence {
    /// Constructor
    pub fn new(sequence: S) -> Self {
        Self {
            sequence,
        }
    }
}

impl<S> Sequence for EnumeratedSequence<S>
where S: Sequence {
    type Term = (usize, S::Term);
    fn terms(&self) -> Box<dyn Iterator<Item = Self::Term> + '_> {
        Box::new(self.sequence.terms().enumerate())
    }
    fn approx_num_terms(&self) -> Option<usize> {
        self.sequence.approx_num_terms()
    }
}


#[derive(Debug, Clone)]
/// Skip some terms of a [`Sequence`]
pub struct SkippedSequence<S>
where S: Sequence {
    sequence: S,
    n: usize,
}

impl<S> SkippedSequence<S>
where S: Sequence {
    /// Constructor
    pub fn new(sequence: S, n: usize) -> Self {
        Self {
            sequence,
            n,
        }
    }
}

impl<S> Sequence for SkippedSequence<S>
where S: Sequence {
    type Term = S::Term;
    fn terms(&self) -> Box<dyn Iterator<Item = Self::Term> + '_> {
        Box::new(self.sequence.terms().skip(self.n))
    }
    fn approx_num_terms(&self) -> Option<usize> {
        match self.sequence.approx_num_terms() {
            Some(n) if n > self.n => Some(n-self.n),
            Some(_) => Some(0),
            None => None,
        }
    }
}


#[derive(Debug, Clone)]
/// Map a [`Sequence`], term by term
pub struct MappedSequence<S, F, U>
where S: Sequence, F: Fn(S::Term) -> U {
    sequence: S,
    op: F,
}

impl<S, F, U> MappedSequence<S, F, U>
where S: Sequence, F: Fn(S::Term) -> U {
    /// Constructor
    pub fn new(sequence: S, op: F) -> Self {
        Self {
            sequence,
            op,
        }
    }
}

impl<S, F, U> Sequence for MappedSequence<S, F, U>
where S: Sequence, F: Fn(S::Term) -> U {
    type Term = U;
    fn terms(&self) -> Box<dyn Iterator<Item = Self::Term> + '_> {
        Box::new(self.sequence.terms().map(move |t| (self.op)(t)))
    }
    fn approx_num_terms(&self) -> Option<usize> {
        self.sequence.approx_num_terms()
    }
}


#[derive(Debug, Clone)]
/// Scan a [`Sequence`], term by term, using op to change a state value for each term
pub struct ScannedSequence<S, St, F, U>
where S: Sequence, St: Clone, F: Fn(&mut St, S::Term) -> U {
    sequence: S,
    initial: St,
    op: F,
}

impl<S, St, F, U> ScannedSequence<S, St, F, U>
where S: Sequence, St: Clone, F: Fn(&mut St, S::Term) -> U {
    /// Constructor
    pub fn new(sequence: S, initial: St, op: F) -> Self {
        Self {
            sequence,
            initial,
            op,
        }
    }
}

impl<S, St, F, U> Sequence for ScannedSequence<S, St, F, U>
where S: Sequence, St: Clone, F: Fn(&mut St, S::Term) -> U {
    type Term = U;
    fn terms(&self) -> Box<dyn Iterator<Item = Self::Term> + '_> {
        let mut current = self.initial.clone();
        Box::new(self.sequence.terms().map(move |t| (self.op)(&mut current, t)))
    }
    fn approx_num_terms(&self) -> Option<usize> {
        self.sequence.approx_num_terms()
    }
}


#[derive(Debug, Clone)]
/// Add two [`Sequences`](Sequence), term by term, assuming `zero` if one `Sequence` ends early
pub struct TermAddSequence<A, B>
where A: Sequence, B: Sequence<Term=A::Term>, A::Term: Clone + Add<Output=A::Term> {
    sequence1: A,
    sequence2: B,
}

impl<A, B> TermAddSequence<A, B>
where A: Sequence, B: Sequence<Term=A::Term>, A::Term: Clone + Add<Output=A::Term> {
    /// Constructor
    pub fn new(sequence1: A, sequence2: B) -> Self {
        Self {
            sequence1,
            sequence2,
        }
    }
}

impl<A, B> Sequence for TermAddSequence<A, B>
where A: Sequence, B: Sequence<Term=A::Term>, A::Term: Clone + Add<Output=A::Term> {
    type Term = A::Term;
    fn terms(&self) -> Box<dyn Iterator<Item = Self::Term> + '_> {
        Box::new(self.sequence1.terms().zip_longest(self.sequence2.terms()).map(
            |zipped| zipped.reduce(|a, b| a + b)
        ))
    }
    fn approx_num_terms(&self) -> Option<usize> {
        if let (Some(n1), Some(n2)) = (self.sequence1.approx_num_terms(), self.sequence2.approx_num_terms()) {
            Some(std::cmp::max(n1, n2))
        } else {
            None
        }
    }
}


#[derive(Debug, Clone)]
/// Mul two [`Sequences`](Sequence), term by term, assuming `one` if one `Sequence` ends early
pub struct TermMulSequence<A, B>
where A: Sequence, B: Sequence<Term=A::Term>, A::Term: Clone + Mul<Output=A::Term> {
    sequence1: A,
    sequence2: B,
    trailing_ones: bool,
}

impl<A, B> TermMulSequence<A, B>
where A: Sequence, B: Sequence<Term=A::Term>, A::Term: Clone + Mul<Output=A::Term> {
    /// Constructor
    pub fn new(sequence1: A, sequence2: B, trailing_ones: bool) -> Self {
        Self {
            sequence1,
            sequence2,
            trailing_ones,
        }
    }
}

impl<A, B> Sequence for TermMulSequence<A, B>
where A: Sequence, B: Sequence<Term=A::Term>, A::Term: Clone + Mul<Output=A::Term> {
    type Term = A::Term;
    fn terms(&self) -> Box<dyn Iterator<Item = Self::Term> + '_> {
        if self.trailing_ones {
            Box::new(self.sequence1.terms().zip_longest(self.sequence2.terms()).map(
                |zipped| zipped.reduce(|a, b| a * b)
            ))
        } else {
            Box::new(self.sequence1.terms().zip_longest(self.sequence2.terms()).map_while(
                |zipped| zipped.both().map(|(a, b)| a * b)
            ))
        }
    }
    fn approx_num_terms(&self) -> Option<usize> {
        if self.trailing_ones {
            None
        } else {
            match (self.sequence1.approx_num_terms(), self.sequence2.approx_num_terms()) {
                (Some(n1), Some(n2)) => Some(std::cmp::min(n1, n2)),
                (Some(n1), None) => Some(n1),
                (None, Some(n2)) => Some(n2),
                (None, None) => None,
            }
        }
    }
}


#[derive(Debug, Clone)]
/// A [`Sequence`] that composes two `Sequences` with the given `op`, term by term
pub struct TermComposedSequence<A, B, F, U>
where A: Sequence, A::Term: Clone, B: Sequence, B::Term: Clone, F: Fn(A::Term, B::Term) -> U {
    sequence1: A,
    sequence2: B,
    default: (A::Term, B::Term),
    op: F,
}

impl<A, B, F, U> TermComposedSequence<A, B, F, U>
where A: Sequence, A::Term: Clone, B: Sequence, B::Term: Clone, F: Fn(A::Term, B::Term) -> U {
    /// Constructor
    pub fn new(sequence1: A, sequence2: B, default: (A::Term, B::Term), op: F) -> Self {
        Self {
            sequence1,
            sequence2,
            default,
            op,
        }
    }
}

impl<A, B, F, U> Sequence for TermComposedSequence<A, B, F, U>
where A: Sequence, A::Term: Clone, B: Sequence, B::Term: Clone, F: Fn(A::Term, B::Term) -> U {
    type Term = U;
    fn terms(&self) -> Box<dyn Iterator<Item = Self::Term> + '_> {
        Box::new(self.sequence1.terms().zip_longest(self.sequence2.terms()).map(|zipped| {
            let (a, b) = zipped.or(self.default.0.clone(), self.default.1.clone());
            (self.op)(a, b)
        }))
    }
    fn approx_num_terms(&self) -> Option<usize> {
        if let (Some(n1), Some(n2)) = (self.sequence1.approx_num_terms(), self.sequence2.approx_num_terms()) {
            Some(std::cmp::max(n1, n2))
        } else {
            None
        }
    }
}


#[derive(Debug, Clone)]
/// A [`Sequence`] that composes two `Sequences` by performing FOIL-style multiplication
pub struct FoilMulSequence<A, B>
where A: Sequence,
B: Sequence<Term=A::Term>,
A::Term: Clone + Add<Output=A::Term> + Mul<Output=A::Term> {
    sequence1: A,
    sequence2: B,
}

impl<A, B> FoilMulSequence<A, B>
where A: Sequence,
B: Sequence<Term=A::Term>,
A::Term: Clone + Add<Output=A::Term> + Mul<Output=A::Term> {
    /// Constructor
    pub fn new(a: A, b: B) -> Self {
        Self {
            sequence1: a,
            sequence2: b,
        }
    }
}

impl<A, B> Sequence for FoilMulSequence<A, B>
where A: Sequence,
B: Sequence<Term=A::Term>,
A::Term: Clone + Add<Output=A::Term> + Mul<Output=A::Term> {
    type Term = A::Term;
    fn terms(&self) -> Box<dyn Iterator<Item = Self::Term> + '_> {
        let (mut termvec1, mut termvec2) = (vec![], vec![]);
        let terms = self.sequence1.terms()
            .zip_longest(self.sequence2.terms())
            .map(Some)
            .chain(repeat(None))
            .enumerate()
            .map_while(move |(out_idx, zipped)| {

            let (l, r) = zipped.map_or((None, None), EitherOrBoth::left_and_right);
            if let Some(a) = l {
                termvec1.push(a);
            }
            if let Some(b) = r {
                termvec2.push(b);
            }
            foil_idx(out_idx, &termvec1, &termvec2)

        });
        Box::new(terms)
    }
    fn approx_num_terms(&self) -> Option<usize> {
        if let (Some(n1), Some(n2)) = (self.sequence1.approx_num_terms(), self.sequence2.approx_num_terms()) {
            if n1 == 0 && n2 == 0 {
                Some(0)
            } else {
                Some(n1 + n2 - 1)
            }
        } else {
            None
        }
    }
}

fn foil_idx<T>(out_idx: usize, a: &[T], b: &[T]) -> Option<T>
where T: Clone + Add<Output=T> + Mul<Output=T> {
    // Doing foil:
    // - store vectors of the terms
    // - reverse second vector
    // - add multiplied terms together
    let coeffs1 = a.to_owned();
    let mut rev_coeffs2 = b.to_owned();
    rev_coeffs2.reverse();
    let skip2 = out_idx + 1 - rev_coeffs2.len();
    coeffs1.into_iter().skip(skip2).zip(rev_coeffs2).map(|(a, b)| a * b).reduce(|acc, t| acc + t)
}


#[derive(Debug, Clone)]
/// A [`Sequence`] that rectifies a given `Sequence` by performing carrying by a given `modulus`
pub struct CarrySequence<S>
where S: Sequence, S::Term: LocalZero + LocalOne + PartialOrd + Add<Output=S::Term> + Sub<Output=S::Term> {
    sequence: S,
    modulus: S::Term,
}

impl<S> CarrySequence<S>
where S: Sequence, S::Term: LocalZero + LocalOne + PartialOrd + Add<Output=S::Term> + Sub<Output=S::Term> {
    /// Constructor
    pub fn new(sequence: S, modulus: S::Term) -> Self {
        Self {
            sequence,
            modulus,
        }
    }
}

impl<S> Sequence for CarrySequence<S>
where S: Sequence, S::Term: Clone + LocalZero + LocalOne + PartialOrd + Add<Output=S::Term> + Sub<Output=S::Term> {
    type Term = S::Term;
    fn terms(&self) -> Box<dyn Iterator<Item = Self::Term> + '_> {
        let zero = self.modulus.local_zero();
        let one = self.modulus.local_one();
        let mut carry = zero.clone();
        let modulus = self.modulus.clone();
        let terms = self.sequence.terms()
            .map(Some)
            .chain(repeat(None))
            .map_while(move |t| {

            if t.is_none() && carry.is_local_zero() {
                return None;
            }

            let mut t = t.unwrap_or(zero.clone()) + carry.clone();
            carry = zero.clone();
            while t >= modulus {
                carry = carry.clone() + one.clone();
                t = t - modulus.clone();
            }
            while t < zero {
                carry = carry.clone() - one.clone();
                t = t + modulus.clone();
            }
            Some(t)

        });
        Box::new(terms)
    }
    fn approx_num_terms(&self) -> Option<usize> {
        // TODO: Actually this is just a lower bound; try to find a way to efficiently compute this
        //  or else make `approx_num_terms` return a three-state (or more) structure instead of Option<usize>
        if self.modulus.is_local_zero() || self.modulus.is_local_one() {
            None
        } else {
            self.sequence.approx_num_terms()
        }
    }
}



#[cfg(test)]
mod test {

    use super::Sequence;

    #[test]
    fn non_op() {
        let s = vec!['a', 'b', 'c', 'd'];
        let en = s.clone().enumerate();
        assert!(en.is_finite_sequence());
        assert_eq!(en.terms().collect::<Vec<_>>(), vec![(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd')]);
        let sk = s.clone().skip(2);
        assert!(sk.is_finite_sequence());
        assert_eq!(sk.terms().collect::<Vec<_>>(), vec!['c', 'd']);
        let mp = s.clone().term_map(|c| c.to_ascii_uppercase());
        assert!(mp.is_finite_sequence());
        assert_eq!(mp.terms().collect::<Vec<_>>(), vec!['A', 'B', 'C', 'D']);
        let sn = s.clone().term_scan("letter".to_string(), |acc, c| {
            acc.push(c);
            acc.clone()
        });
        assert!(sn.is_finite_sequence());
        assert_eq!(
            sn.terms().collect::<Vec<_>>(),
            vec!["lettera", "letterab", "letterabc", "letterabcd"]
        );
    }

    #[test]
    fn ops() {
        let s0 = |n| n * n;
        let s1 = vec![1, 5, 25];
        let add = s0.term_add(s1.clone());
        assert!(!add.is_finite_sequence());
        assert_eq!(add.truncation(6), vec![1, 6, 29, 9, 16, 25]);
        let mul_no_trailing = s0.term_mul(s1.clone(), false);
        assert!(mul_no_trailing.is_finite_sequence());
        assert_eq!(mul_no_trailing.terms().collect::<Vec<_>>(), vec![0, 5, 100]);
        let mul_trailing = s0.term_mul(s1.clone(), true);
        assert!(!mul_trailing.is_finite_sequence());
        assert_eq!(mul_trailing.truncation(6), vec![0, 5, 100, 9, 16, 25]);
        let foil_mul = s0.foil_mul(s1.clone());
        assert!(!foil_mul.is_finite_sequence());
        assert_eq!(foil_mul.truncation(6), vec![0, 1, 9, 54, 161, 330]);
        let carry0 = s0.carry_with(10);
        assert!(!carry0.is_finite_sequence());
        assert_eq!(carry0.truncation(6), vec![0, 1, 4, 9, 6, 6]);
        let carry1 = s1.carry_with(10);
        assert!(carry1.is_finite_sequence());
        assert_eq!(carry1.terms().collect::<Vec<_>>(), vec![1, 5, 5, 2]);
    }

}