Search code examples
scalasyntaxequivalence

Can scala syntatic sugar make a congruence mod n?


Consider 2+7 == 3+6 (mod 5). Can you some how use scala syntactic sugar to achieve the same in scala code?

Keep in mind that 2+7 and 3+6 are regular scala Int so overriding the + or == to be mod 5 doesn't work. I'm actually interested in more complex congruences on algebras A. I could do A.congruent(a,b), and write that with some nice symbols like A.~(a,b), but I am interested in a == b (A) or a ==(A) b or perhaps A(a == b). Something where the congruence appears inbetween the terms a and b.

The bottom line of my struggles is that the congruence is defined for type A, and a,b are some elements passed to A but not actually of type A. E.g. A might be a group of matrices and the congruence is if individual matrices a and b differ by a scalar i.e. a*b^-1=sI_n. In particular, a, b will live inside of many groups and the congruence will change based on that. So I it isn't possible to simply add a reference within a and b back to A.

Some how the right solution seems to be the mathematical one, label the equivalence with A not the variables a and b. Yet scala syntactic sugar may not have such a sweetness in mind. Any suggestions appreciated.


Solution

  • Try this:

    implicit class ModEquals(a: Int) {
        def %%(n: Int) = new { def ===(b: Int) = (a - b) % n == 0 }
    }
    

    Usage:

    7 %% 3 === 10
    

    This solution enriches Ints with a %% method that takes the congruence. In this example, it's just modulu, but this can easily be extended to anything. The returned object is a class that has an === method defined to implements the equality check.