Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
andymatuschak opened this issue Oct 6, 2012 · 1 comment

Comments

@andymatuschak
Copy link

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.

@andymatuschak
Copy link
Author

Ah, it seems I've just misunderstood: implementing Num isn't supposed to make that work; it's implementing Add that makes that work.

RalfJung pushed a commit to RalfJung/rust that referenced this issue Jun 29, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant