Introduction to Scala Part2 : Collections
Bubu
3,990 views
Traversable: size info
- Operations: isEmpty, nonEmpty, size, and hasDefiniteSize
- Goal: Get some information on the size of the collection
Traversable collections can be finite or infinite. An example of an infinite traversable collection is the stream of natural numbers Stream.from(0).
The method hasDefiniteSize indicates whether a collection is possibly infinite. If hasDefiniteSize returns true, the collection is certainly finite. If it returns false, the collection has not been not fully elaborated yet, so it might be infinite or finite. (Stream will be see, if we have enough time in Course C#03)
> List(1,2,3).size
res0: Int = 3
Determine If It's an Empty List or Not
Determine If a List Is Big
Create your playground on Tech.io
This playground was created on Tech.io, our hands-on, knowledge-sharing platform for developers.
Suggested playgrounds
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package fp101.tp02.collections
object ExerciceSizeInfo {
/**
*
* Should return is a List is Empty
* isEmpty should not use List.isEmpty method
*
*/
def isEmpty[T](l: List[T]): Boolean = ???
/**
*
* Return a Boolean value:
* - true if the number of element of the list is equal or superior to the threshold
* - false otherwise
*
*/
def isBig[T](l: List[T], threshold: Int): Boolean = ???
}