Tuesday, February 2, 2010

Blocks within for-comprehensions

In another example of uniformity it is possible to use blocks within a for-comprehension when creating a generator or making an assignment. The basic form of a for-comprehension is
  1. for {i <- generator 
  2.      if guard
  3.      j = assignment } yield result

The generator, guard, assignment and result are all expressions which means they can all be blocks or simple statements. Most commonly you will see them as simple statements:
  1. scala> for {i <- 1 to 10
  2.      |      if i % 2 == 0
  3.      |      j = i } yield j
  4. res50: scala.collection.immutable.IndexedSeq[Int] = IndexedSeq(2, 4, 6, 8, 10)

But since they are expressions they can be more complex:
  1. scala> for {  
  2.      |  i <- { 
  3.      |     val start = nextInt(3)
  4.      |     val end = nextInt(10)+start
  5.      |     start to end
  6.      |  }
  7.      |  if {
  8.      |    val cut = nextInt(3)+1
  9.      |    i % cut == 0
  10.      |  }
  11.      |  j = {
  12.      |    val x = i+1
  13.      |    x / 2
  14.      |  }
  15.      |  }  yield {
  16.      |    // do a debug println
  17.      |    println(j)
  18.      |  j
  19.      |  }
  20. 1
  21. 1
  22. 2
  23. 3
  24. res53: scala.collection.immutable.IndexedSeq[Int] = IndexedSeq(1, 1, 2, 3)

2 comments:

  1. Something goes wrong with escaping:
    &-
    should be
    <-

    ReplyDelete
  2. Thank you for noticing. It is fixed now

    ReplyDelete