Introduction to Scala Part2 : Collections
Bubu
6,483 views
Open Source Your Knowledge, Become a Contributor
Technology knowledge has to be shared and made accessible for free. Join the movement.
List
List creation
- List.apply
> List.apply(1, 2, 3, 4)
res53: List[Int] = List(1, 2, 3, 4)
- List.::
> 1 :: 2 :: 3 :: 4 :: Nil
res6: List[Int] = List(1, 2, 3, 4)
- Nil
object Nil extends List[Nothing] with Product with Serializable
Some method of List
- List.range
List.range(1, 5)
res54: List[Int] = List(1, 2, 3, 4)
- List.fill
List.fill(5)('a')
res57: List[Char] = List(a, a, a, a, a)
List.fill(5)('a')
res57: List[Char] = List(a, a, a, a, a)
- List.concat
> List.concat(List('a', 'b'), List('c'))
res60: List[Char] = List(a, b, c)
Lists - Complexity
- Insert at front: o(1)
- Insert at end: o(n)
createList
should return a List create by ListUtil
should add e as first element of l
should add e as last element of l
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 ExerciceList {
/**
*
* Create a List of Int with the :: operator
* The parameter Int* is the Scala syntax for String ... args in Java
*
* hint: Int* is a Seq of Int
*
* a function echo(words: String*) is a function that takes a sequence of arguments such as:
* echo("hello", "world", "!")
*
* the words parameter is named a "Repeated Parameter" and could be see as a Seq of String
*
* To use a sequence "s" as a reapeated parameter, you have to use this syntax: s: _*
* for example:
* val s = Seq("Hello", "World", "!")
*
* echo(s: _*)
*
*/
def createList(x: Int*): List[Int] = ???
/***
*
* Create a method in ListUtil object such as:
* > ListUtil(1, 2, 3, 4, 5) return a List(1, 2, 3, 4, 5)
*/
Enter to Rename, Shift+Enter to Preview