Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package fundeps
- /**
- * So in Scala - we can enforce functional dependencies by making use of implicit object
- * object definitions - this tutorial is at the following URL:
- * Credit: Miles Sabin
- * http://www.chuusai.com/2011/07/16/fundeps-in-scala/
- */
- // Say we have a function that accepts three parameterised types, but rules as for that the third
- // type can be dependant on the other types:
- // Matrix x Matrix = Matrix
- // Matrix x Vector = Vector
- // Matrix x Int = Matrix
- // Int x Matrix = Matrix
- // This is how we do it:
- // Dummy definitions
- trait Matrix
- trait Vector
- trait MultDep[-A, -B, C] extends Function2[A, B, C]
- // Note - A and B above need to be contravariant because....
- object Methods {
- def mult[A, B, C](a : A, b : B)(implicit instance : MultDep[A, B, C]) : C =
- instance(a, b)
- }
- object Runner {
- import Methods.mult
- implicit object mmm extends MultDep[Matrix, Matrix, Matrix] {
- def apply(m1 : Matrix, m2 : Matrix) : Matrix = sys.error("TODO")
- }
- implicit object mvv extends MultDep[Matrix, Vector, Vector] {
- def apply(m1 : Matrix, v2 : Vector) : Vector = sys.error("TODO")
- }
- implicit object mim extends MultDep[Matrix, Int, Matrix] {
- def apply(m1 : Matrix, i2 : Int) : Matrix = sys.error("TODO")
- }
- implicit object imm extends MultDep[Int, Matrix, Matrix] {
- def apply(i1 : Int, m2 : Matrix) : Matrix = sys.error("TODO")
- }
- def main(args: Array[String]) {
- // Type annotations soley to verify that the correct result type has been inferred
- val r1 : Matrix = mult(new Matrix {}, new Matrix{}) // Compiles
- val r2 : Vector = mult(new Matrix {}, new Vector{}) // Compiles
- val r3 : Matrix = mult(new Matrix {}, 2) // Compiles
- val r4 : Matrix = mult(2, new Matrix {}) // Compiles
- // This next one doesn't compile ...
- //val r5 : Matrix = mult(new Matrix {}, new Vector{})
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement