Skip to content

Instantly share code, notes, and snippets.

@thyeem
Created March 21, 2020 19:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thyeem/282402f7fbf2155366bbe089fbb9b3be to your computer and use it in GitHub Desktop.
Save thyeem/282402f7fbf2155366bbe089fbb9b3be to your computer and use it in GitHub Desktop.
use std::ops::{Add, Div, Mul, Range, Rem, Shl, Shr, Sub};
pub trait Uint:
Add<Output = Self>
+ Sub<Output = Self>
+ Mul<Output = Self>
+ Div<Output = Self>
+ Rem<Output = Self>
+ Shl<Output = Self>
+ Shr<Output = Self>
+ From<u8>
+ PartialEq
+ PartialOrd
+ Ord
+ Eq
+ Copy
{
}
impl<U> Uint for U where
U: Add<Output = U>
+ Sub<Output = U>
+ Mul<Output = U>
+ Div<Output = U>
+ Rem<Output = U>
+ Shl<Output = U>
+ Shr<Output = U>
+ From<u8>
+ PartialEq
+ PartialOrd
+ Ord
+ Eq
+ Copy
{
}
pub fn sum_range<T>(range: &Range<T>) -> T
where
T: Uint,
Range<T>: Iterator<Item = T>,
{
let sum: T = (range.start..range.end).fold(T::from(0), |sum, i| sum + i);
sum
}
fn main() {
println!("{:?}", sum_range::<u16>(&(1..101)));
}
@thyeem
Copy link
Author

thyeem commented Mar 21, 2020

Simple integer trait without the help of num_traits

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment