Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

scala Iterable#map vs. Iterable#flatMap

What is the difference between the map and flatMap functions of Iterable?

like image 944
Landon Kuhn Avatar asked Jun 29 '09 18:06

Landon Kuhn


People also ask

What is iterable in Scala?

Iterable: A base trait for iterable collections. This is a base trait for all Scala collections that define an iterator method to step through one-by-one the collection's elements. [...] This trait implements Iterable's foreach method by stepping through all elements using iterator.

What is iterator Scala?

An iterator is a way to access elements of a collection one-by-one. It resembles to a collection in terms of syntax but works differently in terms of functionality. An iterator defined for any collection does not load the entire collection into the memory but loads elements one after the other.

Is Scala iterator lazy?

Unlike operations directly on a concrete collection like List , operations on Iterator are lazy. A lazy operation does not immediately compute all of its results.

What is collections iterable?

An Iterable is a collection of elements that can be accessed sequentially. In Dart, an Iterable is an abstract class, meaning that you can't instantiate it directly. However, you can create a new Iterable by creating a new List or Set .


2 Answers

The above is all true, but there is one more thing that is handy: flatMap turns a List[Option[A]] into List[A], with any Option that drills down to None, removed. This is a key conceptual breakthrough for getting beyond using null.

like image 52
kikibobo Avatar answered Sep 22 '22 04:09

kikibobo


Here is a pretty good explanation:

http://www.codecommit.com/blog/scala/scala-collections-for-the-easily-bored-part-2

Using list as an example:

Map's signature is:

map [B](f : (A) => B) : List[B] 

and flatMap's is

flatMap [B](f : (A) => Iterable[B]) : List[B] 

So flatMap takes a type [A] and returns an iterable type [B] and map takes a type [A] and returns a type [B]

This will also give you an idea that flatmap will "flatten" lists.

val l  = List(List(1,2,3), List(2,3,4))  println(l.map(_.toString)) // changes type from list to string // prints List(List(1, 2, 3), List(2, 3, 4))  println(l.flatMap(x => x)) // "changes" type list to iterable // prints List(1, 2, 3, 2, 3, 4) 
like image 31
agilefall Avatar answered Sep 24 '22 04:09

agilefall