liveBook · Manning

Tail

As explained in Functional Programming in Scala, Second Edition

tail is a list operation that returns all elements except the first, failing when applied to Nil.

tail is a list operation that returns every element after the first. For a nonempty list val mylist = Cons(x, xs), tail returns xs without changing mylist. Because the list is immutable, the result can reuse the existing structure rather than copy it. section 3.3

Removing the first element

Given Cons(1, Cons(2, Nil)), tail returns Cons(2, Nil). Applying tail to Nil fails; the exercise permits using sys.error("message") for that case. The operation takes constant time because it returns the stored tail directly. section 3.3 section 3.1

Implement tail against the custom list definition:

  • Handle Cons by returning its tail field. section 3.3
  • Handle Nil by raising an error rather than returning a list. section 3.3
  • Use the defined List and Nil types, not Scala’s built-in versions. section 3.3
Figure 3.3 Data sharing of lists

Use the data-sharing figure to see how tail preserves the original list while returning a reference to its remaining structure. section 3.3

How Functional Programming in Scala, Second Edition covers it

How deep it goes
Explains constant-time removal and the Nil failure case, but defers alternative error-handling techniques.
Examples
Uses Cons(x, xs), mylist, and the shared structure illustrated by Figure 3.3.
What it assumes
Assumes familiarity with Cons and Nil, while teaching immutable removal through structural sharing.
What you can do after
Build it from scratch as a constant-time operation over the custom Scala List type.
How it connects
Connects tail to singly linked lists, immutable data structures, persistent data structures, and data sharing.

Also explained in

Compare how 3 books explain tail →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Functional Programming in Scala, Second Edition. The section links point to the parts of the book it draws on.