by anon4 · 11y ago · 0 comments
template <int m, int n, int l>
Matrix<m, l>
mul(Matrix<m, n> lhs, Matrix <n, l> rhs)
{...impl...}
And then be able to call it like int m, n, k, l = ... read from file or whatever
Matrix <m, n> m1 = ...;
Matrix <k, l> m2 = ...;
try {
Matrix <int o, int p> m3 = m1 * m2;
// ^ code compiled dynamically
// or loaded from cache, based on
// runtime types of m1 and m2.
// o and p set to the result
// of type inference.
// I could imagine even having
// specialised versions with inline
// assembly for specific dimensions.
} catch (DynamicCompilationException e) {
print("dimensions not compatible");
}
Java could be it, if it had reified generics. You'd create an implementation of Num, or load one from cache, then instantiate the template and attempt to call the mul function.Or you could abuse the invoke dynamic feature - create specialised functions matrixMultiply$m$n$l and classes Matrix$m$n from some other templating language as needed, then do an invoke dynamic based on type. But this would be very cumbersome to use, I think.
(The function that creates the array will be slower since it's not type-stable, but it can generate a type-stable function that's fast.)
case class Dim(size: Int)
trait Matrix[X <: Dim with Singleton, Y <: Dim with Singleton] {
def *[Z <: Dim with Singleton](other: Matrix[Y, Z]):Matrix[X, Z] = ???
}
object Matrix {
def apply[X <: Dim with Singleton, Y <: Dim with Singleton](x: X, y: Y):Matrix[X,Y] = ???
}
val x = Dim(100)
val y = Dim(readFromFile(...))
val z = Dim(37)
val A = Matrix[x.type, y.type](x, y)
val B = Matrix[y.type, z.type](y, z)
A * A // compile error
A * B // ok