Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- object ForTranslations extends App {
- /**
- * Adapted from Scala Language Specification section 6.19
- */
- type Vec = Vector[Double]
- type Matrix = Vector[Vec]
- def transpose(xss: Matrix) = {
- for (i <- Vector.range(0, xss(0).length)) yield
- for (xs <- xss) yield xs(i)
- }
- def scalarProduct(xs: Vec, ys: Vec) = {
- var acc = 0.0
- for ((x, y) <- xs zip ys) acc = acc + x * y
- acc
- }
- /* 0 0 */
- def Multiply0(xss: Matrix, yss: Matrix): Matrix = {
- for (xs <- xss) yield
- for (yst <- transpose(yss)) yield
- scalarProduct(xs, yst)
- }
- /* 0 1 */
- def Multiply1(xss: Matrix, yss: Matrix): Matrix = {
- xss map(xs =>
- for (yst <- transpose(yss)) yield
- scalarProduct(xs, yst)
- )
- }
- /* 1 0 */
- def Multiply2(xss: Matrix, yss: Matrix): Matrix = {
- for (xs <- xss) yield
- transpose(yss) map (yst =>
- scalarProduct(xs, yst)
- )
- }
- /* 1 1 */
- def Multiply3(xss: Matrix, yss: Matrix): Matrix = {
- xss map(xs =>
- transpose(yss) map (yst =>
- scalarProduct(xs, yst)
- )
- )
- }
- val m0: Matrix = Vector(Vector(1.0, 0.0), Vector(0.0, 1.0))
- val m1: Matrix = Vector(Vector(4.0, 5.0), Vector(6.0, 7.0))
- val res0 = Multiply0(m0, m1)
- val res1 = Multiply1(m0, m1)
- val res2 = Multiply2(m0, m1)
- val res3 = Multiply3(m0, m1)
- println(res0 == res1 && res0 == res2 && res0 == res3)
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement