/* This program demonstrates advanced Rust techniques regarding possibly infinite iterators. It includes procedures that augment the Iterator trait with additional abilities, as well as constructs for creating various iterators such as the empty and singleton iterators, as well as infinite streams defined by co-induction. Certain unsafe features are used to circumvent the need to require the Copy/Clone traits. */ #![allow(dead_code)] use std::ops::Index; //// capturing the empty iterator fn empty() -> impl Iterator { None.into_iter() } //// Iterator over a single item struct Singleton { item : Option, } impl Iterator for Singleton { type Item = T; fn next(&mut self) -> Option { let mut temp = None; core::mem::swap(&mut temp, &mut self.item); temp } } fn single(x:T) -> Singleton { Singleton { item : Some(x) } } //// Capturing a Co-Inductive Definition as an Infinite Interator //// struct CoInduction { base: Option, generator: fn(&T) -> T, // not a closure (no free vars), size known } impl CoInduction { pub fn define(base_case:T, inductive_case: fn(&T)->T) -> Self { CoInduction { base:Some(base_case), generator:inductive_case} } } impl Iterator for CoInduction { type Item = T; fn next(&mut self) -> Option { let mut answer = None; core::mem::swap(&mut answer, &mut self.base); self.base = answer.as_ref().map(&self.generator); answer } //next } //// Limited coinduction takes a generator function that returns an Optional struct LimitedCoInduction where F : Fn(&T) -> Option { base : Option, generator : F, } implOption> LimitedCoInduction { pub fn define(base_case:T, inductive_case: F) -> Self { LimitedCoInduction { base:Some(base_case), generator:inductive_case} } } implOption> Iterator for LimitedCoInduction { type Item = T; fn next(&mut self) -> Option { let mut answer = None; core::mem::swap(&mut answer, &mut self.base); self.base = answer.as_ref().and_then(&self.generator); answer } //next } ///// Generic iterator to generate values by a mutable closure struct GenIterT> { generator : F, } implT> Iterator for GenIter { type Item = T; fn next(&mut self) -> Option { Some((self.generator)()) } } fn generateT>(gen:F) -> GenIter { GenIter { generator : gen } } //////////// Augmenting Iterator with Additional Abilities ///////////// trait CustIterator : Iterator + Sized { fn untilbool>(self,F) -> UntilIter; fn limit(self,n:usize) -> LimitIter { LimitIter { iter : self, limit : n } } fn take_whenbool>(self,f:F) -> Option { let mut uiter = self.until(f); let mut nxt = None; while !uiter.yielded { nxt = uiter.next(); } nxt } fn find_last::Item)->bool>(mut self,mut f:F) -> Option { let mut last = None; let mut next = self.next(); while next.is_some() { if next.as_ref().map(&mut f).unwrap_or(false) { last = next; } next = self.next(); } last } } struct UntilIterbool> { iter : I, yielded : bool, predicate : F, } impl Iterator for UntilIter where I : Iterator, F : FnMut(&I::Item) -> bool { type Item = I::Item; fn next(&mut self) -> Option { if self.yielded { return None; } let nxt = self.iter.next(); if nxt.as_ref().map(&mut self.predicate).unwrap_or(true) { self.yielded = true; } nxt } } struct LimitIter { iter : I, limit : usize, } impl Iterator for LimitIter { type Item = I::Item; fn next(&mut self) -> Option { if self.limit == 0 { return None; } self.limit -= 1; self.iter.next() } } impl CustIterator for I { fn untilbool>(self, pred:F) -> UntilIter { UntilIter { iter : self, yielded : false, predicate : pred, } } } //////////// Strong CoInduction: Assumes All Previous Cases ////////////// /// better term: multibase struct StrongCoInduction { base: Vec, // will contain all previous cases generator: fn(&[T]) -> Option, // function takes slice borrow index: usize, // for iterator (must include base vector) } impl StrongCoInduction { pub fn define(base_case:Vec, inductive_case:fn(&[T])->Option) -> Self { StrongCoInduction { base: base_case, generator: inductive_case, index:0, } }//define }// impl StrongCoInduction /* Unlike with simple CoInduction, we can't just "move" the previous case: All cases generated must be kept in a vector. The iterator must push the newly generated case into a vector as well as return it. This is hard to do without requiring T:Copy or T:Clone. Having the iterator return a borrow (&T) is also difficult because each iteration must *mutate* the induction structure. */ // default, copying iterator impl Iterator for StrongCoInduction { type Item = T; fn next(&mut self) -> Option { if self.index == self.base.len() { let next_item = (self.generator)(self.base.as_slice()); if next_item.is_none() { return None; } next_item.map(|ni|self.base.push(ni)); } self.index += 1; Some(self.base[self.index-1].clone()) } //next } struct SIIter2<'lt,T> { si : &'lt mut StrongCoInduction, } impl<'lt,T> Iterator for SIIter2<'lt,T> { type Item = &'lt T; fn next(&mut self) -> Option { if self.si.index == self.si.base.len() { let next_item = (self.si.generator)(self.si.base.as_slice()); if let Some(ni) = next_item { self.si.base.push(ni); } else { return None; } } self.si.index += 1; let len = self.si.index - 1; let ptr = &self.si.base[len] as *const T; unsafe { Some( &*ptr ) } } } impl<'lt,T> StrongCoInduction { pub fn ref_iter(&'lt mut self) -> SIIter2<'lt,T> { SIIter2 { si : self } } pub fn generate(next_generator: fn(&[T])->Option) -> Self { StrongCoInduction { base:Vec::new(), generator: next_generator, index:0, } }//generate } impl Index for StrongCoInduction { type Output = T; fn index(&self, i:usize) -> &Self::Output { &self.base[i] } } /////////////////// Stream of Prime Numbers //////////////////// fn next_prime(known_primes:&[u64]) -> Option { if known_primes.len()==0 { return Some(2); } let last_prime = known_primes[known_primes.len()-1]; if last_prime==2 { return Some(3);} let mut candidates = LimitedCoInduction::define(last_prime+2, |c|{ if addlimit(*c,2) {Some(c+2)} else {None} }) ; candidates .find(|&c| { known_primes.iter() // test against primes up to sqrt(c) .take_while(|&&p| (p as f64) <= (c as f64).powf(0.5) + 1.0) .all(|p| c%p != 0) }) }//next_prime //known_primes.par_iter(), parallel iterators available with Rayon crate fn primes() -> StrongCoInduction { StrongCoInduction::define(vec![2,3,5,7,11], next_prime) } fn prime_factors(x:u64) -> Vec { primes().ref_iter() .take_while(|&&p|p<=x) .filter(|&&p|x%p==0) .map(|p|*p) .collect() } fn prime_factorization(x:u64) -> Vec { let temp = primes().ref_iter() .take_while(|&&p|p<=x) .find(|&&p|x%p==0) .map(|p|*p); if let Some(p) = temp { let mut rest = prime_factorization(x/p); rest.push(p); rest } else { Vec::new() } } // decompose x into powers of 2 fn binary_factors(x:u64) -> Vec { CoInduction::define((1,x), |(p,n)|(2*p, n/2)) .take_while(|&(_,n)|n>0) .filter(|(_,n)| n%2==1) .map(|(p,_)|p) .collect() } fn main() { // Fibonacci numbers: let mut fibs = CoInduction::define( (0,1), // base case as a pair |&(a,b)| (b,a+b)) // "recursive" case .map(|(_,b)|b); // take only the b fibs.nth(10) // returns Option .map(|f|println!("the 11th Fibnonacci number is {}",f)); println!("first 100 primes:"); primes() .take(100) .for_each(|p|print!("{} ",p)); // must run stream std::env::args().nth(1) // command-line arguments .map(|s| // s is a string s.parse::() .map(|n|{ // n is a u64 println!("\nprime factors of {}: {:?}",n, prime_factors(n)); println!("prime factorization of {}: {:?}",n,prime_factorization(n)); println!("binary factors of {}: {:?}",n,binary_factors(n)); })); println!("\nfast_fib(10): {:?}", fast_fib(10)); println!("fast_fib(11): {:?}", fast_fib(11)); println!("fast_fib(12): {:?}", fast_fib(12)); println!("fast_fib(30): {:?}", fast_fib(30)); println!("fast_fib(100): {:?}", fast_fib(100)); println!("power {:?}", power(2u64,15,(|x,y|{print!("{}*{} ",x,y); x*y}),1,intlimit)); println!("powerbig {:?}", power(2u64,100,|x,y|x*y,1,intlimit)); primes().ref_iter().take(100).for_each(|x|print!("{} ",x)); println!(); generate(||1).limit(10).for_each(|x|print!("{} ",x)); println!(); }//main // alt version of fibonacci sequence (not as efficient) fn fibonacci() -> StrongCoInduction { StrongCoInduction::define(vec![1,1], |fibs|{ match fibs { [..,a,b] if addlimit(*a,*b)=> Some(a+b), _ => None, } //let a = fibs[fibs.len()-2]; //let b = fibs[fibs.len()-1]; //a+b }) } //fibonacci sequence // smart fibonacci fn mmult(m1:&[u64;4], m2:&[u64;4]) -> [u64;4] { let ([a,b, c,d], [e,f, g,h]) = (m1,m2); [a*e+b*g, a*f+b*h, c*e+d*g, c*f+d*h] } const ID:[u64;4] = [1,0,0,1]; const FIB:[u64;4] = [1,1,1,0]; fn power(basis:T, exponent:usize, multiplier:fn(&T,&T)->T, identity:T, limit:fn(&T)->bool) -> Option { LimitedCoInduction::define((identity,basis,exponent,&multiplier), |(ax,fct,n,mult)|{ if !limit(fct) { return None; } let nfct = mult(fct,fct); if n%2==1 { Some((mult(ax,fct), nfct, n/2,*mult)) } else { Some((*ax,nfct,n/2,*mult)) } }) .take_when(|&(_,_,n,_)|n==0) .map(|(x,_,_,_)|{println!("current ax: {:?}",x); x}) } fn intlimit(x:&u64) -> bool { let m = (u64::MAX as f64).sqrt(); (*x as f64) < m } fn multlimit(a:u64, b:u64) -> bool { let m = u64::MAX / a; b <= m } fn addlimit(a:u64, b:u64) -> bool { let m = u64::MAX - a; b <= m } fn mmlimit(a:&[u64;4], b:&[u64;4]) -> bool { if multlimit(a[0],b[0]) { let ab = a[0]*b[0]; if multlimit(a[1],b[2]) { let cd = a[1]*b[2]; if addlimit(ab,cd) { return true; } } } false } fn fast_fib(n:usize) -> Option { if n<2 { return Some(1); } LimitedCoInduction::define((ID,FIB,n-1), |(ax,fct,m)|{ if !mmlimit(fct,fct) { return None; } let nfct = mmult(fct,fct); if m%2==1 { Some((mmult(ax,fct),nfct,m/2)) } else { Some((*ax,nfct,m/2)) } }) .take_when(|&(_,_,m)|m==0) .map(|(m,_,_)|m[0]) }