Sunday 24 August 2014

Scala Note 17: Sequence Comprehension


Comprehensions have the formfor (enumsyield e, where enums refers to a semicolon-separated list of enumerators. An enumerator is either a generator which introduces new variables, or it is a filter. A comprehension evaluates the body e for each binding generated by the enumerators enum and returns a sequence of these values.

For example,


object ComprehensionTest1 extends Application {
  def even(from: Int, to: Int): List[Int] =
    for (i <- List.range(from, to) if i % 2 == 0) yield i
  Console.println(even(0, 20))
}

Comprehensions are not restricted to lists.Every datatype that supports the operations filtermap, and flatMap (with the proper types) can be used in sequence comprehensions.


Reference:
http://www.scala-lang.org/old/node/111.html

No comments:

Post a Comment