Skip to content

num::Num implementations not searched for binary operation implementations #3685

Description

@andymatuschak

Perhaps this is behaving as designed, but I found it surprising. I guess I imagined that + was just syntax sugar for num::Num's add() method.

I implemented num::Num on (T, T), where T's bound by num::Num and Copy. But I couldn't add two such tuples together with + (see compile error, below), only with add().

The source:

type Duple<T: num::Num Copy> = (T, T);
impl<T: num::Num Copy> Duple<T>: num::Num {
    pure fn add(other: &Duple<T>) -> Duple<T> { 
        let (a1, b1) = self;
        let (a2, b2) = *other;
        (a1 + a2, b1 + b2)
    }
    pure fn sub(other: &Duple<T>) -> Duple<T> { 
        let (a1, b1) = self;
        let (a2, b2) = *other;
        (a1 - a2, b1 - b2)
    }
    pure fn mul(other: &Duple<T>) -> Duple<T> { 
        let (a1, b1) = self;
        let (a2, b2) = *other;
        (a1 * a2, b1 * b2)
    }
    pure fn div(other: &Duple<T>) -> Duple<T> { 
        let (a1, b1) = self;
        let (a2, b2) = *other;
        (a1 / a2, b1 / b2)
    }
    pure fn modulo(other: &Duple<T>) -> Duple<T> { 
        let (a1, b1) = self;
        let (a2, b2) = *other;
        (a1 % a2, b1 % b2)
    }
    pure fn neg() -> Duple<T> { 
        let (a1, b1) = self;
        (-a1, -b1)
    }

    pure fn to_int() -> int { 
        let (a, b) = self;
        a.to_int()*a.to_int() + b.to_int()*b.to_int()
    }
    static pure fn from_int(n: int) -> Duple<T> {
        let a: T = num::from_int(n);
        (a, a)
    }
}

fn Duple<T: num::Num Copy>(a: T, b: T) -> Duple<T> { (a, b) }

fn main() {
    let a = Duple(3, 4);
    let b = Duple(4, 5);
    // The following line causes a compile error:
    //let c = a + b;
    // But this works fine:
    let c = a.add(&b);
    io::println(int::str(c.to_int()));
}

The compile error in question:

duple.rs:49:16: 49:21 error: binary operation + cannot be applied to type `(int,int)`
duple.rs:49         let c = a + b;

This is on Rust built from f96a2a2 on Mac OS 10.8.2.

Activity

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

      Issue actions