Tuesday, February 18, 2014

Flatmap

  • flatMap is map then flatten
  • flatten requires that each element is traversable
  • flatMap has something to do with burrito


  • Table of contents...



    flatten

    Flatten reduces one level of any Traversable
    List(List(1),List(2),List(3))
    	.flatten //List(1, 2, 3) (result)
    Option is Traversable with 0 or 1 elements
    Some("A").size //1 (result)
    None.size //0 (result)
    List(Some(1),Some(2),Some(3))
    	.flatten //List(1, 2, 3) (result)
    Flatten can be applied to any Traversable
    List(Map(1->3),Map(1->8),Map(5->"A"))
    	.flatten //List((1,3), (1,8), (5,A)) (result)
    flatten can be applied to Nil
    Nil.flatten //List() (result)


    flatten and map

    define items...
    val items = List(List("X"),List(2),List(3))
    items //List(List(X), List(2), List(3)) (result)
    typeOf(items) //List[List[Any]] (result)
    and function foo. Function must return a traversable
    def foo(x : List[Any]) : List[String]= List("foo(" + x + ")")
    apply map to each item
    val mapitems = items.map(foo)
    mapitems
    Output
    List(List(foo(List(X))), List(foo(List(2))), List(foo(List(3))))

    typeOf(mapitems) //List[List[String]] (result)
    apply flatten to the result of map
    val flatmapitems = mapitems.flatten
    flatmapitems
    Output
    List(foo(List(X)), foo(List(2)), foo(List(3)))

    typeOf(flatmapitems) //List[String] (result)


    flatMap

    flatMap is map then flatten...
    val flatmapitems2 = items.flatMap(foo)
    flatmapitems2
    Output
    List(foo(List(X)), foo(List(2)), foo(List(3)))

    typeOf(flatmapitems2) //List[String] (result)


    flatMap usecases

    join few lists...

    No comments:

    Post a Comment