Skip to content

relaxing the trait bounds on Complex::Add and friends #124

Open
@sarah-quinones

Description

@sarah-quinones

at the moment, all the core arithmetic operations for Complex require the Num bound to be satisfied
https://docs.rs/num-complex/latest/num_complex/struct.Complex.html#impl-Add-for-Complex%3CT%3E

this is stronger than it needs to be, and implementing that can be difficult for new numerical types like qd::Double<f64>, due to the Num::from_str_radix being nontrivial to implement

would it be acceptable to relax the constraint to Add<Output = Self> for addition, Sub<Output = Self> for subtraction, and Mul<Output = Self> + Add<Output = Self> + Sub<Output = Self> for multiplication?

Activity

cuviper

cuviper commented on Mar 11, 2024

@cuviper
Member

I think we can do that safely, without any breaking change even, but I do worry about relaxing too far. Relaxing in one direction becomes a limitation in the other, that it leaves little room for making new implementation choices. Plus, a long list of constraints is more of a burden for both the reader and the maintainer.

Maybe we should just add a local trait like:

pub trait ComplexNum: PartialEq + Zero + One + NumOps {}

That is everything from Num except for from_str_radix. The only place we actually use that method is when implementing it for Complex itself. We might also want to split out NumOps and drop Rem, since that's pretty weird for Complex, and we only use it for our own Rem and for div_trunc.

I think it's also fine if a type only implements Num::from_str_radix for "easy" radices at first, or even an unconditional Err if it's really too hard.

redweasel

redweasel commented on Apr 12, 2025

@redweasel

please do this. I don't see, why addition is not allowed for types which e.g. don't implement division (because they are from a mathematical ring like exact integers).
Although one must be a bit careful to avoid recursive definitions, which appear quickly when doing this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Development

      No branches or pull requests

        Participants

        @cuviper@sarah-quinones@redweasel

        Issue actions

          relaxing the trait bounds on Complex::Add and friends · Issue #124 · rust-num/num-complex