liveBook · Manning

List

As explained in Functional Programming in Scala, Second Edition

A list is an ordered collection whose elements are linked sequentially and whose structure is preserved by list-processing operations.

A list is an ordered, immutable collection represented by either Nil or a nonempty Cons containing a head element and a tail list. Pure operations return new lists instead of changing their inputs. section 3.1

Listing 3.1 Singly linked lists
package fpinscala.datastructures
 
enum List[+A]:                            #1
  case Nil                                #2
  case Cons(head: A, tail: List[A])       #3
 
object List:                              #4
  def apply[A](as: A*): List[A] =         #5
    if as.isEmpty then Nil
    else Cons(as.head, apply(as.tail*))

The definition makes the recursive structure explicit: List is polymorphic, Nil represents emptiness, and Cons links a head to the remaining list. section 3.1

List-processing functions preserve or deliberately transform this structure:

  • map changes every element while preserving the list's shape. section 3.3.3
  • filter removes elements that fail a predicate. section 3.3.3
  • flatMap maps each element to a list and inserts the resulting lists into one final list. section 3.3.3
  • Generalized list functions replace repeated explicit recursion with reusable operations. section 3.3.3

Duplicating each element with flatMap

Applying flatMap to List(1, 2, 3) with i => List(i, i) produces List(1, 1, 2, 2, 3, 3), retaining input order while expanding each element. section 3.3.3

How Functional Programming in Scala, Second Edition covers it

How deep it goes
Defines Nil and Cons, explains head and tail, and practices map, filter, flatMap, and generalized list processing.
Examples
Uses Nil, Cons, integer and string lists, element transformations, predicate filtering, paired-list addition, and flatMap duplication.
What it assumes
Assumes basic Scala syntax while introducing data constructors, polymorphic types, immutable values, and list-processing patterns.
What you can do after
Build it from scratch with Nil and Cons, then implement reusable map, filter, flatMap, and generalized list functions.
How it connects
Connects immutable data structures with pure functions, recursion, polymorphism, map, filter, and flatMap.

Also explained in

Compare how 21 books explain list →

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.