liveBook · Manning

Nonempty list

As explained in Functional Programming in Scala, Second Edition

A nonempty list is a list data structure constrained to contain at least one element.

A nonempty list is a list data structure constrained to contain at least one element. Representing it as a head and tail makes the constraint visible in its type. section 12.4.1

Accumulating validation errors

Web-form validation can return several failures at once. Replacing List[String] with NonEmptyList[String] rules out Invalid(Nil), because every invalid result must contain an error. The trade-off is algebraic: NonEmptyList supports associative combination, but cannot provide a Monoid identity value. section 12.4.1 section 12.9

Since combining two nonempty lists always remains nonempty, NonEmptyList has a Semigroup instance. Its Applicative validation combines two Invalid values with combine, while preserving a Valid result when both inputs succeed. section 12.4.1

case class NonEmptyList[+A](head: A, tail: List[A]):
  def toList: List[A] = head :: tail
 
object NonEmptyList:
  def apply[A](head: A, tail: A*): NonEmptyList[A] =
    NonEmptyList(head, tail.toList)

Inspect the Scala representation: a required head stores the first element, while the tail stores any remaining elements. section 12.4.1

How Functional Programming in Scala, Second Edition covers it

How deep it goes
Defines head-and-tail representation, associative combination, and the missing Monoid identity; stops short of broader list operations.
Examples
Demonstrates web-form validation that accumulates name, birthdate, and phone-number errors.
What it assumes
Assumes lists and type classes, while motivating Semigroup from the failed attempt to define a Monoid identity.
What you can do after
Builds a nonempty list and applies associative error combination in an accumulating Validated computation.
How it connects
Connects NonEmptyList to Validated, Applicative, Semigroup, and Monoid through accumulating validation errors.

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.