Lesson 8 of 15

Lists

Lists

Scala lists are immutable sequences. Create them with List(...):

val nums = List(1, 2, 3, 4, 5)
println(nums.length)  // 5
println(nums.head)    // 1
println(nums.tail)    // List(2, 3, 4, 5)

Prepend with ::

val more = 0 :: nums
println(more)  // List(0, 1, 2, 3, 4, 5)

foldLeft

foldLeft accumulates a result over the list:

val sum = List(1, 2, 3, 4, 5).foldLeft(0)((acc, x) => acc + x)
println(sum)  // 15

Your Task

Write a function sumList that takes a List[Int] and returns the sum of all elements using foldLeft.

JS Transpiler loading...
Loading...
Click "Run" to execute your code.