Introduction to Scala Part2 : Collections
Bubu
6,421 views
Open Source Your Knowledge, Become a Contributor
Technology knowledge has to be shared and made accessible for free. Join the movement.
Traversable: Subdivision operations
- Operations: splitAt, span, partition, groupBy
- Goal: split the elements of this collection into several sub-collections.
> List(1,2,3,4,5).splitAt(3)
res0: (List[Int], List[Int]) = (List(1, 2, 3),List(4, 5))
Tuple2 type: (List[Int], List[Int]) = Tuple2[List[Int],List[Int]]
TupleN[T1,..,Tn](_1: T1, _2: T2, ..., _n: Tn)
val t = new Tuple2[Int,Int](2, 3)
// a short hand is:
val t = (2, 3)
// To access values:
t._1 // 2
t._2 // 3
> List(1,3,2,5,4).span(x => x < 3) // put all element in one list until predicate is false, from that point it puts all the elements in the second list
res1: (List[Int], List[Int]) = (List(1),List(3, 2, 5, 4))
scala> List(1,3,2,5,4).partition(x => x < 3) // put all element that valid the predicate in one list and the others in a second list
res2: (List[Int], List[Int]) = (List(1, 2),List(3, 5, 4))
> val l = List(1,3,2,5,4).map(x => if(x % 2 == 0) ("even", x) else ("odd", x))
l: List[(String, Int)] = List((odd,1), (odd,3), (even,2), (odd,5), (even,4))
scala> l.groupBy(x => x._1)
res3: scala.collection.immutable.Map[String,List[(String, Int)]] =
Map(odd -> List((odd,1), (odd,3), (odd,5)), even -> List((even,2), (even,4)))
should split at position n
groupByHouse GoT characters
Open Source Your Knowledge: become a Contributor and help others learn. Create New Content
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
package fp101.tp02.collections
object ExerciceSubdivision {
/**
* Without using l.splitAt
*
* Splits this list into two at a given position.
*
*
*/
def splitAt[T](l: List[T], n: Int): Tuple2[List[T],List[T]] = ???
/**
*
* Group game of throne characters by lastName
* => "Stark" -> List(Arya Stark, Eddard Stark, ...)
*
* hint: use List.groupBy method
*/
def groupByHouse = {
val l = List(
"John Snow",
"Daenerys Targaryen",
"Arya Stark",
"Ramsay Bolton",
"Sansa Stark",
"Cersei Lannister",
"Tyrion Lannister",
"Joffrey Baratheon",
Enter to Rename, Shift+Enter to Preview