liveBook · Manning

Partial function

As explained in Functional Programming in Scala, Second Edition

A partial function is a function defined for only some values in its input domain.

A partial function is defined for only some inputs. Its input type permits values for which the function has no meaningful result, as with mean on an empty sequence. section 4.2

Mean of an empty sequence

A naive mean implementation can throw an exception when xs.isEmpty, return Double.NaN, or use another sentinel. These choices let errors propagate silently, burden callers with checks, and fail for polymorphic results where no sentinel exists. Returning Option makes the missing case explicit: mean(xs) yields None for an empty sequence and Some(value) otherwise. section 4.2 section 4.3.1

Option turns partiality into data that callers must handle deliberately. Its map, flatMap, filter, getOrElse, and orElse operations factor out repeated error-handling control flow and allow computations to be chained without exceptions. section 4.3.1

Common partial operations represented with Option include:

  • Looking up a key in a map returns an optional value. section 4.3.1
  • Retrieving the first or last element of a possibly empty sequence returns an Option. section 4.3.1
  • Chaining lookup, transformation, filtering, and a default can produce a usable result without explicit exception handling. section 4.3.1
Listing 4.2 The Option data type
enum Option[+A]:
  case Some(get: A)
  case None
 
  def map[B](f: A => B): Option[B]                   #1
  def flatMap[B](f: A => Option[B]): Option[B]       #2
  def getOrElse[B >: A](default: => B): B            #3
  def orElse[B >: A](ob: => Option[B]): Option[B]    #4
  def filter(f: A => Boolean): Option[A]             #5

Inspect the core Option operations used to represent and compose partial results. section 4.3.1

How Functional Programming in Scala, Second Edition covers it

How deep it goes
Defines partiality, contrasts exception and sentinel strategies, and demonstrates Option-based composition without exploring formal theory.
Examples
Uses mean, map lookup, headOption, lastOption, and employee-department lookup as concrete examples.
What it assumes
Assumes typed function inputs and introduces the mismatch between permitted inputs and meaningful results.
What you can do after
Apply it via Option to represent missing results and compose partial computations without exception-driven control flow.
How it connects
Connects partial functions to exceptions, Option, Either, higher-order functions, and polymorphic code.

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.