Introduction to Scala Part2 : Collections
Bubu
6,474 views
Open Source Your Knowledge, Become a Contributor
Technology knowledge has to be shared and made accessible for free. Join the movement.
Traversable: Sub-collection retrieval operations
- Operations:
- tail,
- init,
- slice,
- take,
- drop,
- takeWhile,
- dropWhile,
- filter,
- filterNot,
- withFilter.
- Goal: return some sub-collection identified by an index range or some predicate.
> List(1,2,3,4,5).tail
res1: List[Int] = List(2, 3, 4, 5)
> List(1,2,3,4,5).init
res2: List[Int] = List(1, 2, 3, 4)
> List(1,2,3,4,5).take(2)
res3: List[Int] = List(1, 2)
> List(1,2,3,4,5).dropWhile(x => x < 3)
res4: List[Int] = List(3, 4, 5)
> List(1,2,3,4,5).filter(x => x %2 == 0)
res5: List[Int] = List(2, 4)
What about withFilter ?
> List(1,2,3,4,5).withFilter(x => x %2 == 0)
res6: scala.collection.generic.FilterMonadic[Int,List[Int]] = scala.collection.TraversableLike$WithFilter@550fa96f
> List(1,2,3,4,5).withFilter(x => x %2 == 0).map(x => x)
res7: List[Int] = List(2, 4)
return the tail of a list
return the init of a list
return a list of the n first elements of l
return the list without the first n elements
return the ood elements of the list
return the even elements of the list
take longest prefix of elements that satisfy a predicate.
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 ExerciceSubCollectionRetrieval {
/**
*
* Without using List.tail operation
* write a function tail that selects all elements except the first.
*
*/
def tail[T](l: List[T]): List[T] = ???
/**
* Without using List.init operation
* write a function init that selects all elements except the last.
*
*/
def init[T](l: List[T]): List[T] = ???
/**
* Without using List.take operation
* Write a function take that selects the first n elements of the l list.
*/
def take[T](l: List[T], n: Int) = ???
/**
* Without using List.drop operation
* Write a function drop that selects all the elements of l excepts the first n elements
*/
def drop[T](l: List[T], n: Int) = ???
Enter to Rename, Shift+Enter to Preview