O'Reilly logo

Learning Functional Data Structures and Algorithms by Raju Kumar Mishra, Atul Khot

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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:

List head and tail

We usually write the second clause as ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required