#odd #primitive #check #even #methods #interface #value

parity

为原始数值类型提供 is_even 和 is_odd 方法

1 个不稳定版本

0.1.0 2023年10月13日
0.0.0 2019年9月21日

#741 in 数学

CC0 许可证

7KB
86

Parity

提供检查值奇偶性的接口。

通常,您会直接使用取模运算符来检查一个数字是偶数还是奇数。像 Ruby 这样的语言允许调用方法名 even?odd?。这个包在所有原始数值类型上提供了 is_evenis_odd 方法。现在您可以编写如下代码

// importing the trait is required to use the method on primitives
use parity::Parity;

for i in 0..100 {
  if i.is_even() {
    println("{i}");
  }
}

// or even like this
let x : Vec<_> = (0..100).map(u32::is_even).collect();

特质的实现非常简单

pub trait Parity {
    fn is_even(&self) -> bool;
    fn is_odd(&self) -> bool;
}
impl Parity for i32 {
    #[inline]
    fn is_even(&self) -> bool {
        *self & 1 == 0
    }
    #[inline]
    fn is_odd(&self) -> bool {
        *self & 1 != 0
    }
}
// implemented for all numeric primitive types
// ...

内联属性用于允许跨包优化。这意味着使用这些方法与直接使用取模或按位与运算符相比没有额外的成本。

无运行时依赖