Scala extended cycle

  var z = 10
  for (i <- 1 to 3; x = i + 1; y = z - 1) {
    println(x)
    println(y)
    z -= 1
  }

Output:

2 9 3 9 4 9

This is not what I expect. It seems the for loop always saves z = 10. Can someone help me explain this?

0
source share
2 answers

You can check what you are using as below:

scala> import scala.reflect.runtime.{universe => ru}
scala> import ru._
scala> q"""for (i <- 1 to 3; x = i + 1; y = z - 1) {
     |     println(x)
     |     println(y)
     |     z -= 1
     |   }
     | """
res13: reflect.runtime.universe.Tree =
1.to(3).map(((i) => {
  val x = i.$plus(1);
  val y = z.$minus(1);
  scala.Tuple3(i, x, y)
})).foreach(((x$1) => x$1: @scala.unchecked match {
  case scala.Tuple3((i @ _), (x @ _), (y @ _)) => {
    println(x);
    println(y);
    z.$minus$eq(1)
  }
}))

If you see the extended code, I believe that this is enough to convince you that ythere should always be 9.

+2
source

Scala forare not mandatory cycles, they are a common monadic understanding. Each forand for-yieldcorresponds to a sequence of applications of the method foreach, map, flatMapand withFilter.

For example, here:

for (x <- generator) yield { f(x) }

corresponded to

generator.map(x => f(x))

x = ... for -, :

for {
  g <- generator
  x = xRhs
} {
  doBlah()
}

for {
  (g, x) <- for (g <- generator) yield (g, xRhs)
} {
  doBlah()
}

(for (g <- generator) yield (g,xRhs)).foreach{ 
  case (g, x) => doBlah() 
}

, ,

generator.map(g => (g, xRhs)).foreach{ case (g, x) => doBlah() }

( , , ):

def ----- : Unit = println("-" * 40)

{
  var z = 10
  for (i <- 1 to 3; x = i + 1; y = z - 1) {
    // println(s"i = $i , x = $x , y = $y, z = $z")
    println(x)
    println(y)
    z -= 1
  }
}

-----

{
  var z = 10
  for {
    (i, x) <- for (i <- 1 to 3) yield (i, i + 1)
    y = z - 1
  } {
    println(x)
    println(y)
    z -= 1 
  }
}

-----

{
  var z = 10
  for {
    ((i, x), y) <- for ((i, x) <- for (i <- 1 to 3) yield (i, i + 1)) yield ((i, x), z - 1)
  } {
    println(x)
    println(y)
    z -= 1 
  }
}

-----

{
  var z = 10
  for {
    ((i, x), y) <- for ((i, x) <- (1 to 3).map(i => (i, i + 1))) yield ((i, x), z - 1)
  } {
    println(x)
    println(y)
    z -= 1
  }
}

-----

{
  var z = 10
  for {
    ((i, x), y) <- (1 to 3).map(i => (i, i + 1)).map(ix => (ix, z - 1))
  } {
    println(x)
    println(y)
    z -= 1
  }
}

-----

{
  var z = 10
  (1 to 3).map(i => (i, i + 1)).map(ix => (ix, z - 1)).foreach {
    case ((i, x), y) => 
      println(x)
      println(y)
      z -= 1
  }
}

( ) :

  var z = 10
  (1 to 3).map(i => (i, i + 1)).map(ix => (ix, z - 1)).foreach {
    case ((i, x), y) => 
      println(x)
      println(y)
      z -= 1
  }

, z - 1 map foreach. y 9.

? var for -. : var . , , :

  var z = 10
  for (i <- 1 to 3) {
    val x = i + 1
    val y = z - 1
    println(x)
    println(y)
    z -= 1
  }
+2

All Articles