Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- val x = Array.fill[Int](1, 2) = 0
- x(1)(2) += 1
- val x = Vector.fill[Int](1, 2) = 0
- // how do I update this? I want to write something like val newX : Vector[Vector[Int]] = x.add((1, 2), 1)
- // but I'm not sure how
- var c = (for (i <- 0 to 99; j <- 0 to 99) yield (i,j) -> 0).toMap
- var v = Vector.fill(100,100)(0)
- v(82)(49) // Easy enough
- v = v.updated(82, v(82).updated(49, v(82)(49)+1) // Ouch!
- var u = Vector.fill(100*100)(0)
- u(82*100 + 49) // Um, you think I can always remember to do this right?
- u = u.updated(82*100 + 49, u(82*100 + 49)+1) // Well, that's actually better
- import scalaz._
- def at[A](i: Int): Lens[Seq[A], A] = Lens.lensg(a => a.updated(i, _), (_(i)))
- def at2d[A](i: Int, j: Int) = at[Seq[A]](i) andThen at(j)
- val table = Vector.tabulate(3, 4)(_ + _)
- def show[A](t: Seq[Seq[A]]) = t.map(_ mkString " ") mkString "n"
- scala> show(table)
- res0: String =
- 0 1 2 3
- 1 2 3 4
- 2 3 4 5
- scala> show(at2d(1, 2).set(table, 9))
- res1: String =
- 0 1 2 3
- 1 2 9 4
- 2 3 4 5
- scala> val v: Int = at2d(2, 3).get(table)
- v: Int = 5
- scala> show(at2d(2, 2).mod(((_: Int) * 2), table))
- res8: String =
- 0 1 2 3
- 1 2 3 4
- 2 3 8 5
- object UpdatableVector {
- implicit def vectorToUpdatableVector2[T](v: Vector[Vector[T]]) = new UpdatableVector2(v)
- implicit def vectorToUpdatableVector3[T](v: Vector[Vector[Vector[T]]]) = new UpdatableVector3(v)
- implicit def vectorToUpdatableVector4[T](v: Vector[Vector[Vector[Vector[T]]]]) = new UpdatableVector4(v)
- class UpdatableVector2[T](v: Vector[Vector[T]]) {
- def updated2(c1: Int, c2: Int)(newVal: T) =
- v.updated(c1, v(c1).updated(c2, newVal))
- }
- class UpdatableVector3[T](v: Vector[Vector[Vector[T]]]) {
- def updated3(c1: Int, c2: Int, c3: Int)(newVal: T) =
- v.updated(c1, v(c1).updated2(c2, c3)(newVal))
- }
- class UpdatableVector4[T](v: Vector[Vector[Vector[Vector[T]]]]) {
- def updated4(c1: Int, c2: Int, c3: Int, c4: Int)(newVal: T) =
- v.updated(c1, v(c1).updated3(c2, c3, c4)(newVal))
- }
- }
- import UpdatableVector._
- val v2 = Vector.fill(2,2)(0)
- val r2 = v2.updated2(1,1)(42)
- println(r2) // Vector(Vector(0, 0), Vector(0, 42))
- val v3 = Vector.fill(2,2,2)(0)
- val r3 = v3.updated3(1,1,1)(42)
- println(r3) // etc
Add Comment
Please, Sign In to add comment