Skip to Content
Mastering Functional Programming
book

Mastering Functional Programming

by Anatolii Kmetiuk
August 2018
Intermediate to advanced
380 pages
10h 2m
English
Packt Publishing
Content preview from Mastering Functional Programming

For

The for statement is a little bit more unconventional. In fact, the for statement is syntactic sugar for an application of the foreach, map, and flatMap methods. For example, take a look at the following expression:

scala> val list = 0 to 3list: scala.collection.immutable.Range.Inclusive = Range 0 to 3scala> val result =     | for {     |   e <- list     |   list2 = 0 to e     |   e2 <- list2     | } yield (e, e2)result: scala.collection.immutable.IndexedSeq[(Int, Int)] = Vector((0,0), (1,0), (1,1), (2,0), (2,1), (2,2), (3,0), (3,1), (3,2), (3,3))scala> println(result.mkString("\n"))(0,0)(1,0)(1,1)(2,0)(2,1)(2,2)(3,0)
(3,1)(3,2)(3,3)

The preceding for expression expands to the following method applications:

scala> val result = list.flatMap { e => | val list2 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Learning Functional Programming

Learning Functional Programming

Jack Widman

Publisher Resources

ISBN: 9781788620796Supplemental Content