rust-num / num-complex

Complex numbers for Rust
Apache License 2.0
232 stars 50 forks source link

Proposal: Complex helper constructors #78

Open ElectricCoffee opened 4 years ago

ElectricCoffee commented 4 years ago

I have a simple request based on an actual use-case that I needed: helper functions to create reals and imaginaries directly.

impl<T: Clone + Num> Complex<T> {
  fn re(re: T) -> Complex<T> {
    Complex::new(re, T::zero())
  }

  fn im(im: T) -> Complex<T> {
    Complex::new(T::zero(), im)
  }
}

With these two constructors we'd be able to simply write Complex::im(2.0) instead of Complex::new(0.0, 2.0), which would make it slightly more ergonomic for the cases where you know for a fact you don't need one of the parts right away, but do need a Complex number.

Similarly (or alternatively) a set of conversion functions from a scalar Num to a complex one would be nice too, so we can write 2.0.to_im() to achieve the same or a similar result.

cuviper commented 4 years ago

You can already use From<T> for Complex<T> for real values, and as usual this enables Into too. However, there's no direct way to do this for pure-imaginary values yet.

I wouldn't use re/im for your suggested helpers, because those collide with the actual field names, which are even public. Maybe from_re/from_im would be OK as more idiomatic constructor names. For to_re/to_im, there could be a trait ToComplex with a blanket impl, although that would idiomatically take references; "into" would be something that takes a direct value.

ElectricCoffee commented 4 years ago

The only reason I suggested the im and re constructors was because of the brevity, I didn't want something to be much longer than new and have it outweigh having the alternative constructors in the first place.

Regarding the From implementation, I must have missed that completely, so good to know!

cuviper commented 4 years ago

The problem with brevity is that it also tends toward ambiguity. I'd rather keep clear, idiomatic methods in the official API, but of course you could write your own brief helpers locally.

ElectricCoffee commented 4 years ago

Another reason for wanting these constructors, is because they could be made const, which into never will be.

And I agree, ambiguity should be avoided.

cuviper commented 4 years ago

Another reason for wanting these constructors, is because they could be made const,

That would be nice, but we can't call T::zero() in const context.

ElectricCoffee commented 4 years ago

right, that's necessary due to the generic nature of the Complex structs