Free Trial

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


Share this Page URL
Help

Chapter 23: For Expressions Revisited > Chapter 23: For Expressions Revisited - Pg. 481

Chapter 23 For Expressions Revisited Chapter 16 demonstrated that higher-order functions such as map , flatMap , and filter provide powerful constructions for dealing with lists. But some- times the level of abstraction required by these functions makes a program a bit hard to understand. Here's an example. Say you are given a list of per- sons, each defined as an instance of a class Person . Class Person has fields indicating the person's name, whether (s)he is male, and his/her children. Here's the class definition: scala> case class Person(name: String, isMale: Boolean, children: Person*) Here's a list of some sample person s: val lara = Person("Lara", false) val bob = Person("Bob", true) val julie = Person("Julie", false, lara, bob) val persons = List(lara, bob, julie) Now, say you want to find out the names of all pairs of mothers and their children in that list. Using map , flatMap and filter , you can formulate the following query: scala> persons filter (p => !p.isMale) flatMap (p => (p.children map (c => (p.name, c.name)))) res0: List[(String, String)] = List((Julie,Lara), (Julie,Bob)) 481