Created
August 2, 2017 17:52
-
-
Save pythoneer/277cca17c32d25923d46ce5232d42902 to your computer and use it in GitHub Desktop.
rust monomoph
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extern crate num; | |
use std::ops::{Add, AddAssign}; | |
use std::fmt::Display; | |
use num::traits::Zero; | |
//an Iterator over types that can be added | |
trait AIterator { | |
type Output: Add + AddAssign + Display + Clone + Zero; | |
fn next(&mut self) -> Self::Output; | |
} | |
//an Iterator from 1 to 10 with integers | |
#[derive(Default)] | |
struct OneToTen { | |
state: i32, | |
} | |
impl AIterator for OneToTen { | |
type Output = i32; | |
fn next(&mut self) -> Self::Output { | |
if self.state < 10 { | |
self.state += 1; | |
} | |
self.state | |
} | |
} | |
//an Iterator from ~3 to ~5 with floats | |
struct ThreeToFive { | |
state: f32, | |
} | |
impl Default for ThreeToFive { | |
fn default() -> Self { | |
ThreeToFive{state: 3_f32} | |
} | |
} | |
impl AIterator for ThreeToFive { | |
type Output = f32; | |
fn next(&mut self) -> Self::Output { | |
if self.state < 5_f32 { | |
self.state += 0.2_f32; | |
} | |
self.state | |
} | |
} | |
fn main() { | |
let one_to_ten = OneToTen::default(); | |
let sum_i = show_iterator_monomorph::<OneToTen>(one_to_ten); | |
println!("sum: {}", sum_i); | |
println!(""); | |
let three_to_five = ThreeToFive::default(); | |
let sum_f = show_iterator_monomorph::<ThreeToFive>(three_to_five); | |
println!("sum: {}", sum_f); | |
} | |
//can print an AIterator and sum up what it is emitting (uses monomorphization) | |
fn show_iterator_monomorph<T>(mut ai: T) -> <T as AIterator>::Output | |
where T: AIterator, | |
{ | |
let mut sum= Zero::zero(); | |
for _ in 1..13 { | |
let next = ai.next(); | |
sum += next.clone(); | |
println!("ai: {}", next); | |
} | |
sum | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment