num-complex icon indicating copy to clipboard operation
num-complex copied to clipboard

Proposal: Complex helper constructors

Open ElectricCoffee opened this issue 4 years ago • 6 comments

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.

ElectricCoffee avatar Mar 31 '20 08:03 ElectricCoffee

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.

cuviper avatar Mar 31 '20 21:03 cuviper

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!

ElectricCoffee avatar Mar 31 '20 21:03 ElectricCoffee

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.

cuviper avatar Apr 01 '20 16:04 cuviper

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.

ElectricCoffee avatar Apr 01 '20 19:04 ElectricCoffee

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.

cuviper avatar Apr 01 '20 20:04 cuviper

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

ElectricCoffee avatar Apr 02 '20 12:04 ElectricCoffee