Guest User

Untitled

a guest
Jan 19th, 2019
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.20 KB | None | 0 0
  1. val x = Array.fill[Int](1, 2) = 0
  2. x(1)(2) += 1
  3.  
  4. val x = Vector.fill[Int](1, 2) = 0
  5. // how do I update this? I want to write something like val newX : Vector[Vector[Int]] = x.add((1, 2), 1)
  6. // but I'm not sure how
  7.  
  8. var c = (for (i <- 0 to 99; j <- 0 to 99) yield (i,j) -> 0).toMap
  9.  
  10. var v = Vector.fill(100,100)(0)
  11. v(82)(49) // Easy enough
  12. v = v.updated(82, v(82).updated(49, v(82)(49)+1) // Ouch!
  13.  
  14. var u = Vector.fill(100*100)(0)
  15. u(82*100 + 49) // Um, you think I can always remember to do this right?
  16. u = u.updated(82*100 + 49, u(82*100 + 49)+1) // Well, that's actually better
  17.  
  18. import scalaz._
  19.  
  20. def at[A](i: Int): Lens[Seq[A], A] = Lens.lensg(a => a.updated(i, _), (_(i)))
  21. def at2d[A](i: Int, j: Int) = at[Seq[A]](i) andThen at(j)
  22.  
  23. val table = Vector.tabulate(3, 4)(_ + _)
  24.  
  25. def show[A](t: Seq[Seq[A]]) = t.map(_ mkString " ") mkString "n"
  26.  
  27. scala> show(table)
  28. res0: String =
  29. 0 1 2 3
  30. 1 2 3 4
  31. 2 3 4 5
  32.  
  33. scala> show(at2d(1, 2).set(table, 9))
  34. res1: String =
  35. 0 1 2 3
  36. 1 2 9 4
  37. 2 3 4 5
  38.  
  39. scala> val v: Int = at2d(2, 3).get(table)
  40. v: Int = 5
  41.  
  42. scala> show(at2d(2, 2).mod(((_: Int) * 2), table))
  43. res8: String =
  44. 0 1 2 3
  45. 1 2 3 4
  46. 2 3 8 5
  47.  
  48. object UpdatableVector {
  49. implicit def vectorToUpdatableVector2[T](v: Vector[Vector[T]]) = new UpdatableVector2(v)
  50. implicit def vectorToUpdatableVector3[T](v: Vector[Vector[Vector[T]]]) = new UpdatableVector3(v)
  51. implicit def vectorToUpdatableVector4[T](v: Vector[Vector[Vector[Vector[T]]]]) = new UpdatableVector4(v)
  52.  
  53. class UpdatableVector2[T](v: Vector[Vector[T]]) {
  54. def updated2(c1: Int, c2: Int)(newVal: T) =
  55. v.updated(c1, v(c1).updated(c2, newVal))
  56. }
  57.  
  58. class UpdatableVector3[T](v: Vector[Vector[Vector[T]]]) {
  59. def updated3(c1: Int, c2: Int, c3: Int)(newVal: T) =
  60. v.updated(c1, v(c1).updated2(c2, c3)(newVal))
  61. }
  62.  
  63. class UpdatableVector4[T](v: Vector[Vector[Vector[Vector[T]]]]) {
  64. def updated4(c1: Int, c2: Int, c3: Int, c4: Int)(newVal: T) =
  65. v.updated(c1, v(c1).updated3(c2, c3, c4)(newVal))
  66. }
  67. }
  68.  
  69. import UpdatableVector._
  70.  
  71. val v2 = Vector.fill(2,2)(0)
  72. val r2 = v2.updated2(1,1)(42)
  73. println(r2) // Vector(Vector(0, 0), Vector(0, 42))
  74.  
  75. val v3 = Vector.fill(2,2,2)(0)
  76. val r3 = v3.updated3(1,1,1)(42)
  77. println(r3) // etc
Add Comment
Please, Sign In to add comment