Tuesday, August 11, 2009

For-comprehensions

The for-comprehension construct is a very powerful way of iterating over collections. In its most basic form it is the java for( var: collection){} loop. As with all flow constructs in Scala, the scala for loop (or more correctly for-comprehension) can return a value. In the case of the for-comprehension it returns Unit (similar to void in Java terms) or a Sequence if yield is used.
  1. scala>val range = 1 to 5
  2. range: Range.Inclusive = Range(1, 2, 3, 4, 5)
  3. // no return value if there is no 'yield' keyword
  4. scala>for( i <- 1 to 10 ) { i + 1 }
  5. // if there is a yield a collection is returned
  6. // the type of collection depends on the input
  7. // here a Range is returned
  8. scala>for( i <- range ) yield i+1
  9. res1: RandomAccessSeq.Projection[Int] = RangeM(2, 3, 4, 5, 6)
  10. // here a list is returned
  11. scala>for( i <- List( "a", "b", "c") ) yield"Word: "+i
  12. res1: List[java.lang.String] = List(Word: a, Word: b, Word: c)
  13. // you can filter the elements that visited in the loop
  14. scala>for( i <- range; if( i % 2 == 0) ) yield i
  15. res2: Seq.Projection[Int] = RangeFM(2, 4)
  16. // this    is more    about creating ranges than loops
  17. scala>for ( i <- 20 until (10,-2) ) yield i
  18. res3: RandomAccessSeq.Projection[Int] = RangeM(20, 18, 16, 14, 12)
  19. // you can string together multiple "generators"
  20. scala>for( i <- range; j <- range) yield (i,j)
  21. res4: Seq.Projection[(Int, Int)] = RangeG((1,1), (1,2), (1,3), (1,4), (1,5), (2,1), (2,2), (2,3), (2,4), (2,5), (3,1), (3,2), (3,3), (3,4), (3,5), (4,1), (4,2), (4,3), (4,4), (4,5), (5,1), (5,2), (5,3), (5\
  22. ,4), (5,5))
  23. // you can also    declar variables as part of the    loop declaration
  24. scala>for( i <- range; j <- 1 to i; k = i-j) yield k
  25. res5: Seq.Projection[Int] = RangeG(0, 1, 0, 2, 1, 0, 3, 2, 1, 0, 4, 3, 2, 1, 0)
  26. // with round brackets '(' and ')' multiple lines will require semi-colons
  27. scala>for (
  28.      | i <- range;
  29.      | j <- 1 to i;
  30.      | k = i-j) yield k
  31. res6: Seq.Projection[Int] = RangeG(0, 1, 0, 2, 1, 0, 3, 2, 1, 0, 4, 3, 2, 1, 0)
  32. // with curly brackets '{' and '}' multiple lines you do not require semi-colons
  33. scala>for {
  34.      | i <- range
  35.      | j <- 1 to i
  36.      | k = i-j}
  37.      | yield{
  38.      | k
  39.      | }
  40. res7: Seq.Projection[Int] = RangeG(0, 1, 0, 2, 1, 0, 3, 2, 1, 0, 4, 3, 2, 1, 0)
  41. scala>for( i <- "enjoy" ) print(i)
  42. enjoy

No comments:

Post a Comment