Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.


  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • DownloadDownload
  • PrintPrint
Share this Page URL
Help

Chapter 23: For Expressions Revisitedย >ย 23.5 Going the other way - Pg. 493

S ECTION 23.5 ยท Going the other way expr 1 foreach ( x => body) A larger example is the expression: for ( x <- expr 1 ; if expr 2 ; y <- expr 3 ) body This expression translates to: expr 1 withFilter ( x => expr 2 ) foreach ( x => expr 3 foreach ( y => body)) For example, the following expression sums up all elements of a matrix rep- resented as a list of lists: var sum = 0 for (xs <- xss; x <- xs) sum += x This loop is translated into two nested foreach applications: var sum = 0 xss foreach (xs => xs foreach (x => sum += x)) 23.5 Going the other way The previous section showed that for expressions can be translated into ap- plications of the higher-order functions map , flatMap , and withFilter . In fact, you could equally well go the other way: every application of a map , flatMap , or filter can be represented as a for expression. Here are im- plementations of the three methods in terms of for expressions. The meth- ods are contained in an object Demo , to distinguish them from the standard operations on List s. To be concrete, the three functions all take a List as parameter, but the translation scheme would work just as well with other collection types: 493