rust-num / num-bigint

Big integer types for Rust
Apache License 2.0
540 stars 188 forks source link

Add powi method for `Sign` enum #289

Open feefladder opened 9 months ago

feefladder commented 9 months ago

The multiplication method is provided, but raising a sign to an integer power is also a common use-case I think?

#[inline]
fn sign_powi<T: Integer>(sign: Sign, pow: T) -> Sign {
  if pow.is_odd() {sign} else {Sign::Plus}
}

or in an impl:

#[inline]
impl Sign {
  fn powi<T: Integer>(&self, pow: T) -> Sign {
    if pow.is_odd() {*self} else {Sign::Plus}
  }
}

I came here, because fraction crate uses Sign, which I use.

cuviper commented 9 months ago

It's not quite that simple since there's also NoSign, but we do have an internal function for this already: https://github.com/rust-num/num-bigint/blob/367481903a56a89eee2bffa5a27f8b9c75bfd40f/src/bigint/power.rs#L9-L21

I was hesitant to add public Sign powers during the initial Pow review, https://github.com/rust-num/num-bigint/pull/54#discussion_r202194456, and I'm still not sure about it. It's not really the intention for Sign to act like a complete mathematical entity on its own. Can you explain more about why fraction would want this? It looks like they have their own Sign anyway.