Tuesday 13 January 2015

Map, Flatten, FlatMap in Scala


1. passing map a function, an anonymous function,to transform each element.
Think of an if statement(guard) as being a filter, so the correct solution is to first filter the collection, and then call map

scala> val fruits = List("apple", "banana", "lime", "orange", "raspberry")
scala> fruits.filter(_.length < 6).map(_.toUpperCase)
res1: List[String] = List(APPLE, LIME) 

2. Use the flatten method to convert a list of lists into a single list.

scala> val list = List("Hello", "world")
scala> list.flatten
res0: List[Char] = List(H, e, l, l, o, w, o, r, l, d)  

3. Use flatMap in situations where you run map followed by flatten
  • You’re using map (or a for/yield expression) to create a new collection from an existing collection. The resulting collection is a list of lists.
  • You call flatten immediately after map.  When you’re in this situation, you can use flatMap instead.
  • flatMap does both the mapping(invoking the provided function, passing in each element)
    and the flattening of the result(extracting out the values from Some and throwing out the None)
  • scala> def subWords(word: String) = List(word, word.tail, word.take(word.length-1))
    scala> words.flatMap(subWords)
    res2: List[String] = List(band, and, ban, start, tart, star, then, hen, the)
    
    val l = List(1, "this", 2, 4.4, 'c')
    l.flatMap{
       case i:Int => Some(i)
       case _ => None
    }
    res1: List[Int] = List(1,2)

No comments:

Post a Comment