
上QQ阅读APP看书,第一时间看更新
FRP – the map() function Marble diagram
In Scala, the map() function performs the following steps one by one:
- Take each element from the source container.
- Apply the given function.
- Create a new container of the same type as the destination container. Here, container means any data structure that can hold more than one element; for instance, a Collection, Option, Either, and so on.
In the Reactive World, we can call this container a data stream, as it emits or consumes the data (or data elements).
Here's the Scala sample code for the map() function:
scala> val numList = List(1,2,3,4,5) numList: List[Int] = List(1, 2, 3, 4, 5) scala> val squaredNumList = numList.map( x => x*x ) squaredNumList: List[Int] = List(1, 4, 9, 16, 25)
Here, the map() function picks up each element from a number list, squares it, and creates a new list with the resultant numbers. Let's represent this map() functional operation in a pictorial form using a Marble diagram:

Here, the source data stream is a List (1,2,3,4,5) and the destination or resulting data stream is also a list with the squared value, that is, List (1, 4, 9, 16, 25).
The data transformation or functional operator is map( x => x*x ).