Skip to content

Support for 'scalar' operations for enums #524

@grover-lc

Description

@grover-lc

It would be useful for me to be able to derive Add-like and Mul-like operations for enums with a fixed Rhs type in order to conveniently express things like disjoint unions of group actions. For example:

#[derive(Mul)]
#[mul(scalar)]
enum Coproduct<S, T> {
    Left(S),
    Right(T),
}

would hopefully generate something like:

impl<R, S, T> std::ops::Mul<R> for Coproduct<S, T>
where
    S: std::ops::Mul<R, Output = S>,
    T: std::ops::Mul<R, Output = T>,
{
    type Output = Self;
    fn mul(self, rhs: R) -> Self::Output {
        match self {
            Self::Left(l) => Self::Left(l * rhs),
            Self::Right(r) => Self::Right(r * rhs),
        }
    }
}

(of course the attribute name could be something else).

I may be up for trying to implement this myself if welcome.

As a side note, I was also wondering if there is a particular reason why structs of unit type don't have derivable ops? Could they not just be the trivial group/ring i.e. MyUnit * MyUnit = MyUnit?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions