Getting value at index

We cannot do random indexing on a linked list. We have to traverse the list and keep counting until we reach the element or are presented with an error.

Before we look at the method, let's look at Scala's tuple matching. For example, consider the following snippet:

scala> val tup = (1, l) 
tup: (Int, ch02.mylist.List[Int]) = (1,::(1,::(2,::(3,::(4,Nil))))) 
 
scala> tup match { 
     |   case (i, x :: xs) => s"i = ${i}, x = ${x}" 
     | } 
<console>:19: warning: match may not be exhaustive. 
It would fail on the following input: (_, Nil) 
       tup match { 
       ^ 
res20: String = i = 1, x = 1 

The warning is issued, as we are not handling the case, when the second element of the tuple is an empty list. As the preceding code snippet is merely illustrative, ...

Get Learning Functional Data Structures and Algorithms now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.