Skip to content

How Strong the Evidence Is

A parsed type is evidence that a check happened. How much that evidence is worth depends on how the type is built. This note continues Parse Dont Validate; part of Parsing and evidence.

Smart constructors and newtypes

Most languages can’t prove a predicate such as x > 0 (see Refinement Types). The usual substitute is a constructor that validates once and a type that records that it happened.

In TypeScript, a brand plus validation emulates a refinement type:

declare const positive: unique symbol

type Positive = number & {
    readonly [positive]: true
}

function makePositive(x: number): Positive | undefined {
    return x > 0 ? x as Positive : undefined
}

After construction, Positive carries evidence that validation happened, but TypeScript itself hasn’t mathematically proved the predicate.

The evidence is also only a convention. -5 as Positive compiles anywhere the type is in scope, so the brand guarantees as much as the team’s discipline about casts: keep the one as Positive inside makePositive’s module and forbid casts elsewhere with a lint rule. Rust’s private field, below, is enforced by the compiler instead.

In Rust, the normal approach is a newtype with a smart constructor:

struct Positive(u32);

impl Positive {
    fn new(x: u32) -> Option<Self> {
        if x > 0 {
            Some(Self(x))
        } else {
            None
        }
    }
}

With a private field, outside code can’t construct an invalid Positive. This is an invariant enforced through encapsulation and the type system.

Thompson (PDF, chapter 16, “Abstract data types”, sections 16.2, 16.7 and 16.8) presents the same boundary as the classical abstract data type: for an ordered search Tree a or a duplicate-free newtype Set a = Set [a], the module export list hides both the data constructors and internal helpers such as join whose preconditions (t1 < t2) an arbitrary caller could violate. Hiding a constructor normally costs callers pattern matching; Parsons (PDF, chapter 10, “Type Safety Back and Forth”) recovers it in GHC with PatternSynonyms, keeping UnsafeNonZero private behind nonZero :: (Num a, Eq a) => a -> Maybe (NonZero a) while exporting a unidirectional pattern NonZero a <- UnsafeNonZero a that matches values without constructing them.

Which wrappers to introduce in the first place, and how each language spells them, is in Newtypes And Simple Values.

Names are not type safety

Alexis King’s “Names are not type safety” (HTML) addresses an important subtlety with newtype/opaque wrappers: merely giving a String another type name prevents mixing values, but doesn’t establish an invariant such as “this is a valid email.” This is the distinction between type identity and value validity. (Lexi Lambda)

The article contrasts two ways of getting safety from a type, which King calls intrinsic and extrinsic:

  • Constructive (intrinsic). The type’s shape makes invalid values impossible to build. A non-empty list defined as a head plus a tail (data NonEmpty a = a :| [a]) has no empty value, so nothing needs checking anywhere.
  • By encapsulation (extrinsic). A newtype with a hidden constructor and a smart constructor that checks. The guarantee is only as good as that one module: the compiler checks that every value went through the module, not that the module’s check is right.

Two consequences of the difference are easy to miss:

  • Consumers lose exhaustiveness checking. King’s example is a number from one to five. As a sum type with five constructors, a function over it is checked for missing cases. As a newtype over Int, every consumer needs an error "impossible" branch, and if a sixth value is added later, the constructive version stops compiling while the newtype version compiles and fails at run time.
  • Encapsulated values are tokens. The module issues them and is the only place they can be redeemed. That restricts where the invariant can be broken to one module, which King says you can then test thoroughly (property-based tests or fuzzing), but it’s still weaker than a proof.

Prefer constructive types when they’re cheap, and fall back on encapsulation when the invariant can’t be expressed by shape (a valid email address). An analogy: a constructive type is a plug whose shape won’t fit the wrong socket, while encapsulation is an inspector’s sign-off, as trustworthy as the inspector.

Hidden constructors

An encapsulated type is only as safe as its only constructor, and most languages generate extra constructors without asking:

  • Derived instances. King shows that deriving Generic or Read for a NonEmpty newtype lets anyone build NonEmpty [] (read "NonEmpty []" works). As Thompson notes (section 16.2, “Type classes: showing values and equality”), Haskell module export lists cannot hide type class instances once declared, so any Read or Generic instance leaks across the module boundary even when the data constructor does not.
  • copy on case classes. In Scala, Username.from(s) can validate, but username.copy(value = "") bypasses it. Volpe (PDF, chapter 1, “Strongly-typed functions”) closes the hole with a sealed abstract case class, which has no copy and no public apply, and notes that zero-cost @newtype wrappers remove copy while still leaving Email("foo") and .coerce[Email] open unless paired with a smart constructor or Refined predicate.
  • Deserialization. Bloch (PDF, chapter 12, Item 88) points out that Java’s readObject is effectively another public constructor: a crafted byte stream can create an object that no normal constructor would allow, so readObject must check everything the constructor checks. JSON decoders that write fields directly have the same problem.
  • Mutable inputs. A constructor that checks a mutable argument and keeps a reference to it can be invalidated afterwards; see What Belongs In Types.

Evidence without runtime cost

Matt Noonan’s “Ghosts of Departed Proofs” (PDF) examines the relationship between compile-time guarantees and runtime checks. Its premise is that a precondition can be verified and evidence of that verification encoded in types, so later operations don’t have to check it again. It describes encoding sophisticated preconditions in types while retaining no runtime overhead for the proof representation. (Input | Output)

The motivating example is merging sorted lists, which is only correct if both lists were sorted with the same comparator. Roughly:

newtype SortedBy comp a = SortedBy a

sortBy  :: ((a -> a -> Ordering) ~~ comp) -> [a] -> SortedBy comp [a]
mergeBy :: ((a -> a -> Ordering) ~~ comp)
        -> SortedBy comp [a] -> SortedBy comp [a] -> SortedBy comp [a]

f ~~ comp attaches a type-level name, comp, to the comparator, and SortedBy comp [a] is a list tagged with the fact that it was sorted by the comparator of that name. mergeBy therefore accepts only lists sorted by the comparator it’s given. Names and facts are phantom types, erased at compile time, which is where “no runtime overhead” comes from. The ghosts in the title are these proofs: present while type checking, gone at runtime.

The scheme depends on who gets to choose a name (section 2.4, “On the Danger of Naming a Ghost”). Names come from a function with a rank-2 type, so the library invents a fresh name for every comparator and the caller can’t pick it. If callers could name values themselves (any_name :: a -> (a ~~ name)), they could give two different comparators the same name, and mergeBy would accept lists sorted in opposite orders. It’s the hidden-constructor problem again, at the type level. Parsons (chapter 10, “Type Safety Back and Forth”, and chapter 11) highlights Noonan’s justified-containers library as a self-contained application of the same device: checking membership in a map yields a Key ph k sharing an existential phantom ph with Map ph k a, so lookupJustified :: Key ph k -> Map ph k a -> a is total without Maybe and remains valid even after mapping over the map’s values.

Library sources

  • King 2020, Names are not type safety – intrinsic (constructive) versus extrinsic (encapsulation-based) safety, newtypes as tokens, and derived instances that break the abstraction; on Names are not type safety and Hidden constructors
  • Noonan 2018, Ghosts of Departed Proofs (Functional Pearl) (doi:10.1145/3242744.3242755) – preconditions as phantom types on newtype wrappers, with the sortBy and mergeBy example, and section 2.4 on naming; on Evidence without runtime cost
  • Parsons 2023, Production Haskell – chapter 10, “Type Safety Back and Forth”, on keeping UnsafeNonZero private while exporting a unidirectional pattern NonZero via PatternSynonyms, and justified-containers (lookupJustified :: Key ph k -> Map ph k a -> a in chapter 11) for total map lookups via phantom proofs; on Smart constructors and newtypes and Evidence without runtime cost
  • Thompson 2023, Haskell: The Craft of Functional Programming, 3rd Edition – chapter 16, “Abstract data types”: section 16.2 on hiding constructors behind module exports and why type class instances (Eq, Show) cannot be hidden once declared; sections 16.7, “Search trees” (keeping both Node and the precondition-assuming helper join unexported), and 16.8, “Sets” (newtype Set a = Set [a] preserving order and uniqueness across operations); on Smart constructors and newtypes and Hidden constructors
  • Volpe 2021, Practical FP in Scala, 2nd Edition – chapter 1, “Strongly-typed functions” (“Value classes”, “Newtypes” including .coerce and “newtypes do not solve validation”, sealed abstract case class against copy, “Refinement types” and “Runtime validation”); on Smart constructors and newtypes, Names are not type safety and Hidden constructors
  • Bloch 2018, Effective Java, 3rd Edition – chapter 12, “Serialization”, Item 88, “Write readObject methods defensively”; on Hidden constructors
  • Allen et al. 2016, Haskell Programming from First Principles – chapter 12, “Signaling adversity”, sections 12.2 and 12.3: smart constructors (mkPerson) that return Maybe or Either; on Smart constructors and newtypes
  • Skinner 2023, Effective Haskell – chapter 5, section “Choosing What to Export”: subsection “Smart Constructors” exports SortedList (getSorted) and makeSortedList but not the constructor; subsection “Phantom Types and Export Lists” tags User with unexported empty types Authenticated and Unauthenticated, so only authenticate can produce a User Authenticated; on Smart constructors and newtypes and Evidence without runtime cost
  • Maguire 2018, Thinking with Types: Type-Level Programming in Haskell – section 7.2, “Scoping Information with Existentials”: the ST trick, where a rank-2 runST gives each block a fresh type the caller can’t name, the same device as the naming function in Noonan’s section 2.4, on Evidence without runtime cost; sections 8.1, “Coercions”, and 8.2, “Roles”: coerce could turn a Map k v into a Map (Reverse k) v and break its ordering, which a nominal role prevents (type role BST nominal for your own types), on Hidden constructors