List head and tail
Here is the simplest List
method that gets the first element, that is, head
of the list:
scala> def head[A](list: List[A]): A = list match { | case Nil => sys.error("tail of empty list") | case ::(x, _) => x | } head: [A](list: ch02.mylist.List[A])A
We perform a pattern match on the list. The first clause case Nil => sys.error("tail of empty list")
matches when the list is empty. An empty list will not have a first element so we raise an exception:
case ::(x, _) => x
This clause matches when there are one or more elements in the list.
The following diagram shows how the pattern match works:
We usually write the second clause as follows:
case x :: _ => x
This reads better. The expression  ::(x, _)
can always be written in infix notation as x :: _
. See http://danielwestheide.com/blog/2012/11/21/the-neophytes-guide-to-scala-part-1-extractors.html
for more information. Here is the revised head...