Created
April 16, 2020 01:08
-
-
Save qryxip/ba214a17da165795c75f52ff10c4047b to your computer and use it in GitHub Desktop.
`alga::general::AbstractMonoid` for `min` and `max`
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
//! ```cargo | |
//! [package] | |
//! name = "min-max-monoid" | |
//! version = "0.0.0" | |
//! authors = ["Ryo Yamashita <[email protected]>"] | |
//! edition = "2018" | |
//! publish = false | |
//! | |
//! [dependencies] | |
//! alga = "0.9.3" | |
//! | |
//! [dev-dependencies] | |
//! static_assertions = "1.1.0" | |
//! pretty_assertions = "0.6.1" | |
//! ``` | |
fn main() {} | |
use alga::general::{AbstractMagma, AbstractMonoid, AbstractSemigroup, Identity, Operator}; | |
use std::cmp; | |
macro_rules! impl_monoid { | |
((($operator:ident, $operate:path, $identity:ident)), ($($ty:ty),*) $(,)?) => { | |
#[derive(Clone, Copy, Debug)] | |
pub struct $operator; | |
impl Operator for $operator { | |
fn operator_token() -> Self { | |
Self | |
} | |
} | |
$( | |
impl AbstractMagma<$operator> for $ty { | |
fn operate(&self, right: &Self) -> Self { | |
$operate(*self, *right) | |
} | |
} | |
impl AbstractSemigroup<$operator> for $ty {} | |
impl Identity<$operator> for $ty { | |
fn identity() -> Self { | |
<$ty>::$identity() | |
} | |
} | |
impl AbstractMonoid<$operator> for $ty {} | |
)* | |
}; | |
(($($monoid:tt),*), $tys:tt $(,)?) => { | |
$(impl_monoid!(($monoid), $tys);)* | |
} | |
} | |
impl_monoid!( | |
((Min, cmp::min, max_value), (Max, cmp::max, min_value)), | |
(u8, u16, u32, u64, u128, usize, i8, i16, i32, i64, i128, isize), | |
); | |
#[cfg(test)] | |
mod tests { | |
use super::{Max, Min}; | |
use alga::general::{AbstractMagma, AbstractMonoid, Identity}; | |
use pretty_assertions::assert_eq; | |
use static_assertions::assert_impl_all; | |
assert_impl_all!(i32: AbstractMonoid<Min>); | |
assert_impl_all!(i32: AbstractMonoid<Max>); | |
#[test] | |
fn test() { | |
assert_eq!(1, AbstractMagma::<Min>::operate(&1, &2)); | |
assert_eq!(2, AbstractMagma::<Max>::operate(&1, &2)); | |
assert_eq!(i32::max_value(), Identity::<Min>::identity()); | |
assert_eq!(i32::min_value(), Identity::<Max>::identity()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment