Advertisement
Guest User

Untitled

a guest
Dec 19th, 2014
146
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.36 KB | None | 0 0
  1. object ForTranslations extends App {
  2.  
  3. /**
  4. * Adapted from Scala Language Specification section 6.19
  5. */
  6.  
  7. type Vec = Vector[Double]
  8. type Matrix = Vector[Vec]
  9.  
  10. def transpose(xss: Matrix) = {
  11. for (i <- Vector.range(0, xss(0).length)) yield
  12. for (xs <- xss) yield xs(i)
  13. }
  14.  
  15. def scalarProduct(xs: Vec, ys: Vec) = {
  16. var acc = 0.0
  17. for ((x, y) <- xs zip ys) acc = acc + x * y
  18. acc
  19. }
  20.  
  21. /* 0 0 */
  22. def Multiply0(xss: Matrix, yss: Matrix): Matrix = {
  23. for (xs <- xss) yield
  24. for (yst <- transpose(yss)) yield
  25. scalarProduct(xs, yst)
  26. }
  27.  
  28. /* 0 1 */
  29. def Multiply1(xss: Matrix, yss: Matrix): Matrix = {
  30. xss map(xs =>
  31. for (yst <- transpose(yss)) yield
  32. scalarProduct(xs, yst)
  33. )
  34. }
  35.  
  36. /* 1 0 */
  37. def Multiply2(xss: Matrix, yss: Matrix): Matrix = {
  38. for (xs <- xss) yield
  39. transpose(yss) map (yst =>
  40. scalarProduct(xs, yst)
  41. )
  42. }
  43.  
  44. /* 1 1 */
  45. def Multiply3(xss: Matrix, yss: Matrix): Matrix = {
  46. xss map(xs =>
  47. transpose(yss) map (yst =>
  48. scalarProduct(xs, yst)
  49. )
  50. )
  51. }
  52.  
  53. val m0: Matrix = Vector(Vector(1.0, 0.0), Vector(0.0, 1.0))
  54. val m1: Matrix = Vector(Vector(4.0, 5.0), Vector(6.0, 7.0))
  55.  
  56. val res0 = Multiply0(m0, m1)
  57. val res1 = Multiply1(m0, m1)
  58. val res2 = Multiply2(m0, m1)
  59. val res3 = Multiply3(m0, m1)
  60. println(res0 == res1 && res0 == res2 && res0 == res3)
  61.  
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement