Code Examples for

Programming in Scala, Fifth Edition

Return to chapter index

14 Working with Lists

Sample run of chapter's interpreter examples

14.1 List literals


// In file working-with-lists/Misc.scala val fruit = List("apples", "oranges", "pears") val nums = List(1, 2, 3, 4) val diag3 = List( List(1, 0, 0), List(0, 1, 0), List(0, 0, 1) ) val empty = List()

14.2 The List type


// In file working-with-lists/Misc.scala val fruit: List[String] = List("apples", "oranges", "pears") val nums: List[Int] = List(1, 2, 3, 4) val diag3: List[List[Int]] = List( List(1, 0, 0), List(0, 1, 0), List(0, 0, 1) ) val empty: List[Nothing] = List()
// In file working-with-lists/Misc.scala // List[Nothing] is also of type List[String]! val xs: List[String] = List()

14.3 Constructing lists


// In file working-with-lists/Misc.scala val fruit = "apples" :: ("oranges" :: ("pears" :: Nil)) val nums = 1 :: (2 :: (3 :: (4 :: Nil))) val diag3 = (1 :: (0 :: (0 :: Nil))) :: (0 :: (1 :: (0 :: Nil))) :: (0 :: (0 :: (1 :: Nil))) :: Nil val empty = Nil
// In file working-with-lists/Misc.scala val nums = 1 :: 2 :: 3 :: 4 :: Nil

14.4 Basic operations on lists


scala> Nil.head java.util.NoSuchElementException: head of empty list
// In file working-with-lists/InsertionSort1.scala def isort(xs: List[Int]): List[Int] = if xs.isEmpty then Nil else insert(xs.head, isort(xs.tail)) def insert(x: Int, xs: List[Int]): List[Int] = if xs.isEmpty || x <= xs.head then x :: xs else xs.head :: insert(x, xs.tail)

14.5 List patterns


scala> val List(a, b, c) = fruit val a: String = apples val b: String = oranges val c: String = pears
scala> val a :: b :: rest = fruit val a: String = apples val b: String = oranges val rest: List[String] = List(pears)
// In file working-with-lists/InsertionSort2.scala def isort(xs: List[Int]): List[Int] = xs match case List() => List() case x :: xs1 => insert(x, isort(xs1)) def insert(x: Int, xs: List[Int]): List[Int] = xs match case List() => List(x) case y :: ys => if x <= y then x :: xs else y :: insert(x, ys)

14.6 First-order methods on class List


List(1, 2) ::: List(3, 4, 5) // List(1, 2, 3, 4, 5) List() ::: List(1, 2, 3) // List(1, 2, 3) List(1, 2, 3) ::: List(4) // List(1, 2, 3, 4)
// In file working-with-lists/Misc.scala xs ::: ys ::: zs
// In file working-with-lists/Misc.scala xs ::: (ys ::: zs)
def append[T](xs: List[T], ys: List[T]): List[T]
def append[T](xs: List[T], ys: List[T]): List[T] = xs match case List() => ??? case x :: xs1 => ???
case List() => ys
// In file working-with-lists/Misc.scala def append[T](xs: List[T], ys: List[T]): List[T] = xs match case List() => ys case x :: xs1 => x :: append(xs1, ys)
List(1, 2, 3).length // 3
val abcde = List('a', 'b', 'c', 'd', 'e') abcde.last // e abcde.init // List(a, b, c, d)
scala> List().init java.lang.UnsupportedOperationException: init of empty list at ... scala> List().last java.util.NoSuchElementException: last of empty list at ...
abcde.reverse // List(e, d, c, b, a)
abcde // List(a, b, c, d, e)
xs.reverse.reverse equals xs
xs.reverse.init equals xs.tail.reverse xs.reverse.tail equals xs.init.reverse xs.reverse.head equals xs.last xs.reverse.last equals xs.head
// In file working-with-lists/Reverse1.scala def rev[T](xs: List[T]): List[T] = xs match case List() => xs case x :: xs1 => rev(xs1) ::: List(x)
abcde.take(2) // List(a, b) abcde.drop(2) // List(c, d, e) abcde.splitAt(2) // (List(a, b),List(c, d, e))
abcde.apply(2) // c (rare in Scala)
abcde(2) // c (rare in Scala)
abcde.indices // Range 0 until 5
List(List(1, 2), List(3), List(), List(4, 5)).flatten // List(1, 2, 3, 4, 5) fruit.map(_.toList).flatten // List(a, p, p, l, e, s, o, r, a, n, g, e, // s, p, e, a, r, s)
scala> List(1, 2, 3).flatten 1 |List(1, 2, 3).flatten | ^ | No implicit view available from | Int => IterableOnce[B] | where, B is a type variable.
abcde.indices.zip(abcde) // Vector((0,a), (1,b), (2,c), (3,d), (4,e))
val zipped = abcde.zip(List(1, 2, 3)) // List((a,1), (b,2), (c,3))
abcde.zipWithIndex // List((a,0), (b,1), (c,2), (d,3), (e,4))
zipped.unzip // (List(a, b, c),List(1, 2, 3))
abcde.toString // List(a, b, c, d, e)
abcde.mkString("[", ",", "]") // [a,b,c,d,e] abcde.mkString("") // abcde abcde.mkString // abcde abcde.mkString("List(", ", ", ")") // List(a, b, c, d, e)
val buf = new StringBuilder abcde.addString(buf, "(", ";", ")") // (a;b;c;d;e)
val arr = abcde.toArray // Array(a, b, c, d, e) arr.toList // List(a, b, c, d, e)
xs.copyToArray(arr, start)
val arr2 = new Array[Int](10) // Array(0, 0, 0, 0, 0, 0, 0, 0, 0, 0) List(1, 2, 3).copyToArray(arr2, 3) arr2 // Array(0, 0, 0, 1, 2, 3, 0, 0, 0, 0)
val it = abcde.iterator it.next() // a it.next() // b
// In file working-with-lists/Misc.scala def msort[T](less: (T, T) => Boolean) (xs: List[T]): List[T] = def merge(xs: List[T], ys: List[T]): List[T] = (xs, ys) match case (Nil, _) => ys case (_, Nil) => xs case (x :: xs1, y :: ys1) => if less(x, y) then x :: merge(xs1, ys) else y :: merge(xs, ys1) val n = xs.length / 2 if n == 0 then xs else val (ys, zs) = xs.splitAt(n) merge(msort(less)(ys), msort(less)(zs))
msort((x: Int, y: Int) => x < y)(List(5, 7, 1, 3)) // List(1, 3, 5, 7)
val intSort = msort((x: Int, y: Int) => x < y) // intSort has type List[Int] => List[Int]
val reverseIntSort = msort((x: Int, y: Int) => x > y)
val mixedInts = List(4, 1, 9, 0, 5, 8, 3, 6, 2, 7) intSort(mixedInts) // List(0, 1, 2, 3, 4, 5, 6, 7, 8, 9) reverseIntSort(mixedInts) // List(9, 8, 7, 6, 5, 4, 3, 2, 1, 0)

14.7 Higher-order methods on class List


List(1, 2, 3).map(_ + 1) // List(2, 3, 4) val words = List("the", "quick", "brown", "fox") words.map(_.length) // List(3, 5, 5, 3) words.map(_.toList.reverse.mkString) // List(eht, kciuq, nworb, xof)
words.map(_.toList) // List(List(t, h, e), List(q, u, i, c, k), // List(b, r, o, w, n), List(f, o, x)) words.flatMap(_.toList) // List(t, h, e, q, u, i, c, k, b, r, o, w, n, f, o, x)
List.range(1, 5).flatMap( i => List.range(1, i).map(j => (i, j)) ) // List((2,1), (3,1), (3,2), (4,1), // (4,2), (4,3))
// In file working-with-lists/Misc.scala for i <- List.range(1, 5); j <- List.range(1, i) yield (i, j)
scala> var sum = 0 var sum: Int = 0 scala> List(1, 2, 3, 4, 5).foreach(sum += _) scala> sum val res39: Int = 15
List(1, 2, 3, 4, 5).filter(_ % 2 == 0) // List(2, 4) words.filter(_.length == 3) // List(the, fox)
List(1, 2, 3, 4, 5).partition(_ % 2 == 0) // (List(2, 4),List(1, 3, 5))
List(1, 2, 3, 4, 5).find(_ % 2 == 0) // Some(2) List(1, 2, 3, 4, 5).find(_ <= 0) // None
List(1, 2, 3, -4, 5).takeWhile(_ > 0) // List(1, 2, 3) words.dropWhile(_.startsWith("t")) // List(quick, brown, fox)
List(1, 2, 3, -4, 5).span(_ > 0) // (List(1, 2, 3),List(-4, 5))
def hasZeroRow(m: List[List[Int]]) = m.exists(row => row.forall(_ == 0)) hasZeroRow(diag3) // false
def sum(xs: List[Int]): Int = xs.foldLeft(0)(_ + _)
def product(xs: List[Int]): Int = xs.foldLeft(1)(_ * _)
words.foldLeft("")(_ + " " + _) // " the quick brown fox"
words.tail.foldLeft(words.head)(_ + " " + _) // "the quick brown fox"
def flattenLeft[T](xss: List[List[T]]) = xss.foldLeft(List[T]())(_ ::: _) def flattenRight[T](xss: List[List[T]]) = xss.foldRight(List[T]())(_ ::: _)
scala> def flattenRight[T](xss: List[List[T]]) = | xss.foldRight(List())(_ ::: _) 2 | xss.foldRight(List())(_ ::: _) | ^ | Found: (_$1 : List[T]) | Required: List[Nothing]
def reverseLeft[T](xs: List[T]) = xs.foldLeft(\startValue)(\operation)
// In file working-with-lists/Reverse2.scala def reverseLeft[T](xs: List[T]) = xs.foldLeft(List[T]()) { (ys, y) => y :: ys }
List(1, -3, 4, 2, 6).sortWith(_ < _) // List(-3, 1, 2, 4, 6) words.sortWith(_.length > _.length) // List(quick, brown, the, fox)

14.8 Methods of the List object


List.apply(1, 2, 3) // List(1, 2, 3)
List.range(1, 5) // List(1, 2, 3, 4) List.range(1, 9, 2) // List(1, 3, 5, 7) List.range(9, 1, -3) // List(9, 6, 3)
List.fill(5)('a') // List(a, a, a, a, a) List.fill(3)("hello") // List(hello, hello, hello)
List.fill(2, 3)('b') // List(List(b, b, b), List(b, b, b))
val squares = List.tabulate(5)(n => n * n) // List(0, 1, 4, 9, 16) val multiplication = List.tabulate(5,5)(_ * _) // List(List(0, 0, 0, 0, 0), // List(0, 1, 2, 3, 4), List(0, 2, 4, 6, 8), // List(0, 3, 6, 9, 12), List(0, 4, 8, 12, 16))
List.concat(List('a', 'b'), List('c')) // List(a, b, c) List.concat(List(), List('b'), List('c')) // List(b, c) List.concat() // List()

14.9 Processing multiple lists together


(List(10, 20).zip(List(3, 4, 5))).map { (x, y) => x * y } // List(30, 80)
(List(10, 20).lazyZip(List(3, 4, 5))).map(_ * _) // List(30, 80)
(List("abc", "de").lazyZip(List(3, 2))).forall(_.length == _) // true (List("abc", "de").lazyZip(List(3, 2))).exists(_.length != _) // false

14.10 Understanding Scala's type inference algorithm


msort((x: Char, y: Char) => x > y)(abcde) // List(e, d, c, b, a)
abcde.sortWith(_ > _) // List(e, d, c, b, a)
scala> msort(_ > _)(abcde) 1 |msort(_ > _)(abcde) | ^^^ |value > is not a member of Any, but could be made | available as an extension method.
msort[Char](_ > _)(abcde) // List(e, d, c, b, a)
def msortSwapped[T](xs: List[T])(less: (T, T) => Boolean): List[T] = ... // same implementation as msort, // but with arguments swapped
msortSwapped(abcde)(_ > _) // List(e, d, c, b, a)
xss.foldRight(List[T]())(_ ::: _)
xs.foldRight(z)(op)
xss.foldRight(List())(_ ::: _) // this won't compile
(List[T], List[Nothing]) => List[Nothing]

14.11 Exercises

14.12 Conclusion

For more information about Programming in Scala, Fifth Edition (the "Stairway Book"), please visit:

http://www.artima.com/shop/programming_in_scala_5ed

and:

http://booksites.artima.com/programming_in_scala_5ed

Copyright © 2007-2020 Artima, Inc. All rights reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.