I read in Programming in Scala section 23.5 that map, flatMap and filter operations can always be converted into for-comprehensions and vice-versa.
We’re given the following equivalence:
def map[A, B](xs: List[A], f: A => B): List[B] =
for (x <- xs) yield f(x)
I have a value calculated from a series of map operations:
val r = (1 to 100).map{ i => (1 to 100).map{i % _ == 0} }
.map{ _.foldLeft(false)(_^_) }
.map{ case true => "open"; case _ => "closed" }
I’m wondering what this would look like as a for-comprehension. How do I translate it?
(If it’s helpful, in words this is:
- take integers from 1 to 100
- for each, create a list of 100 boolean values
- fold each list with an XOR operator, back into a boolean
- yield a list of 100 Strings “open” or “closed” depending on the boolean
I imagine there is a standard way to translate map operations and the details of the actual functions in them is not important. I could be wrong though.)
Is this the kind of translation you’re looking for?
If desired, the
mapin the definition ofxcould also be translated to an “inner” for-comprehension.In retrospect, a series of chained
mapcalls is sort of trivial, in that you could equivalently callmaponce with composed functions:I find for-comprehensions to be a bigger win when
flatMapandfilterare involved. Considerversus