Chapter 8: Chapter 8. Equality: expressing relationships between data
This introduction explains how types can express relationships between data and why a compiler may need help establishing them.
After this chapter you will be able to
- Properties expressed in types. Explain how types can express properties of data and relationships between values, and why this increases precision and confidence in functions.
- Vector Length Equality. Explain why a dependent-type function such as vector reverse may require an explanation of a relationship between values to the compiler.
- Limits of Boolean equality. Explain what the type of == says and why it does not establish that its Boolean result reflects equality of its inputs.
- First exactLength implementation attempt. Trace the first attempt to implement exactLength, including the length comparison and its two branches.
- Boolean equality and type evidence. Explain why the True branch cannot return input as a Vect len a and what a more precise comparison type must guarantee.
- Equality as dependent data. Explain how EqNat and its Same constructor represent equality between two natural numbers.
- Unequal arguments and emptiness. Explain why EqNat 3 4 is a valid type but has no values.
- Equality test result guarantee. Explain what checkEqNat returns and what a successful result guarantees about its inputs.
- Recursive Nat comparison cases. Trace how checkEqNat handles zero and successor inputs, including the recursive call and its possible results.
- Successor equality evidence. Explain the role and type of sameS in turning equality evidence for two Nats into evidence for their successors.
- Functions as Equality Proofs. Explain how sameS expresses a proof that equal natural numbers have equal successors.
- Case Splitting Equality Evidence. Trace the implementation of sameS by splitting on its equality evidence and filling the resulting hole.
- Length comparison with evidence. Explain how exactLength uses checkEqNat to compare the input vector’s length with the requested length, and what it does when they differ.
- Equality evidence type refinement. Trace how matching the equality evidence lets exactLength return the input vector at the requested length.
- Generic equality and reflexivity. Explain how Idris’s built-in equality type and Refl express equality, including how evaluation affects equality expressions.
- Congruence of equal values. Explain how cong turns an equality into an equality between results of applying the same function, using the successor example.
- Equality proofs in dependent types. Explain why equality proofs and functions that manipulate them can be useful with dependent types, using natural-number expressions in vector types or the sameS example.
- Length-preserving vector reversal. Describe the type and recursive rules for reversing a vector, including how the empty case is implemented.
- Recursive case type mismatch. Explain the type mismatch encountered when implementing the nonempty reverse case and why it is surprising.
- Type checking by evaluation. Explain how Idris compares an expression’s type with its expected type after evaluation.
- Addition with unknown arguments. Explain why 1 + k evaluates to S k while k + 1 remains plus k 1 when k is unknown, and describe how the REPL can reveal this behavior.
- Reverse length equality. Describe the length-type mismatch in myReverse and explain how plusCommutative identifies an equality that could be used as a rewrite rule.
- Equality rewriting in reverse. Explain how rewrite uses plusCommutative to make the result of myReverse type-check, including how k is brought into scope.
- Hole guided helper extraction. Trace how a hole in myReverse exposes the vector-length mismatch and becomes a helper function.
- Separated rewrite proof. Describe how reverseProof uses a rewrite to reconcile the lengths and how the helper is simplified and kept local.
- Addition order and reduction. Explain why the order of the length arguments in append’s return type determines whether the empty-vector case reduces directly.
- Rewrites for swapped append. Describe why the swapped-length append needs rewrites and how the Prelude’s addition facts and sym support them.
- Equality as evidence. Explain how an equality type guarantees that two values are equal and what Refl contributes to that guarantee.
- Impossibility and inequality evidence. Explain what evidence of inequality must establish and how a function returning Void expresses impossibility.
- Void and impossible inputs. Explain how Void can express that an input or claimed fact is impossible.
- Impossible equality proof. Describe how the section proves that 2 + 2 cannot equal 5 using an impossible equality pattern.
- Totality of negative proofs. Explain why a function returning Void must be total to establish that its input is impossible.
- Decidable properties and evidence. Explain decidability and how Dec gives more precise results than Maybe for natural-number equality.
- Natural number equality procedure. Trace how checkEqNat constructs a Dec result for zero and successor cases.
- Successor inequality contradiction. Explain how noRec proves that unequal predecessors have unequal successors.
- Reusable decidable equality interface. Describe how the Prelude’s DecEq interface provides a reusable alternative to type-specific equality checks, including its use in exactLength.
- Evidence from equality tests. Explain what a Yes prf result from decEq guarantees and how that differs from using Boolean equality.
What it builds on
- Type-level functions: calculating types (chapter 6) · Functions can calculate types using first-class types.
- Adding precision to types: working with vectors (chapter 3) · Vectors carry length information in their types.
- Testing for equality with Eq (chapter 7) · The Eq interface and equality testing with ==.
- Validating Vect lengths (chapter 5) · Validating the lengths of vectors read from the user.
- Using implicit arguments in functions (chapter 3) · Using an implicit argument in a function definition.
- Defining dependent data types (chapter 4) · Dependent types can include data as type arguments.
- Data types and patterns (chapter 3) · Natural numbers can be understood through their Z and S constructors.
- Defining functions by pattern matching (chapter 3) · Functions can be defined by pattern matching and case splitting.
Section by section
Introduction
This introduction explains how types can express relationships between data and why a compiler may need help establishing them.
- Properties expressed in types: Explain how types can express properties of data and relationships between values, and why this increases precision and confidence in functions.
Why it matters: Expressing relationships in types gives function signatures more precise meaning. - Vector Length Equality: Explain why a dependent-type function such as vector reverse may require an explanation of a relationship between values to the compiler.
Why it matters: A relationship that is clear to a programmer may still need to be established for the compiler.
Key terms: first-class types, properties of data, relationships between data, precision, dependent types, reverse, vector lengths, equality
8.1 Guaranteeing equivalence of data with equality types
This section explains why the type of Boolean equality does not guarantee a relationship between inputs and output, using vector length checking as motivation for more expressive types.
- Limits of Boolean equality: Explain what the type of == says and why it does not establish that its Boolean result reflects equality of its inputs.
Why it matters: This distinction explains why a Boolean comparison alone cannot express the relationship needed by the type checker. - Exact vector length check: Describe what exactLength returns when a vector's length matches or differs from a requested length.
Why it matters: This example motivates the need to express relationships between data in types.
Key terms: ==, Bool, Eq interface, type checker, type level, exactLength, Vect, Nothing, Just input
8.1.1 Implementing exactLength, first attempt
This section attempts to implement exactLength and shows why a Boolean equality check cannot establish the vector length required by its return type.
- First exactLength implementation attempt: Trace the first attempt to implement exactLength, including the length comparison and its two branches.
Why it matters: The attempted implementation makes the type-checking problem concrete. - Boolean equality and type evidence: Explain why the True branch cannot return input as a Vect len a and what a more precise comparison type must guarantee.
Why it matters: A comparison result must convey enough information in its type for Idris to accept the intended vector result.
Key terms: exactLength, implicit argument, Vect, Maybe, Nothing, Just, Bool, ==, Eq, Vect m a
8.1.2 Expressing equality of Nats as a type
This section uses the dependent type EqNat to represent equality of natural numbers and explains why unequal arguments produce an empty type.
- Equality as dependent data: Explain how EqNat and its Same constructor represent equality between two natural numbers.
Why it matters: This shows how a type can carry a guarantee about other data. - Unequal arguments and emptiness: Explain why EqNat 3 4 is a valid type but has no values.
Why it matters: The distinction between a valid type and a constructible value is central to using types as guarantees. - Specific type mismatch messages: Describe how the error for EqNat 3 4 can report both the overall mismatch and its more specific difference.
Why it matters: The smaller reported mismatch helps pinpoint the difference inside a larger type error.
Key terms: EqNat, Same, dependent type, Nat, empty type, type error, type mismatch, Z, S
8.1.3 Testing for equality of Nats
This section develops a Nat equality test that returns equality evidence and uses a helper to lift that evidence through successors.
- Equality test result guarantee: Explain what checkEqNat returns and what a successful result guarantees about its inputs.
Why it matters: The result carries usable evidence of equality rather than just reporting a Boolean. - Recursive Nat comparison cases: Trace how checkEqNat handles zero and successor inputs, including the recursive call and its possible results.
Why it matters: The cases show how a recursive equality check constructs evidence as well as detects mismatches. - Successor equality evidence: Explain the role and type of sameS in turning equality evidence for two Nats into evidence for their successors.
Why it matters: Transforming equality evidence lets the recursive check establish equality of the original successor inputs.
Key terms: checkEqNat, EqNat, Maybe, Just, Nothing, Nat, Z, S, case splitting, Same
8.1.4 Functions as proofs: manipulating equalities
This section develops sameS as a function that proves equality of successor values and relates equality evidence to precise function types.
- Functions as Equality Proofs: Explain how sameS expresses a proof that equal natural numbers have equal successors.
Why it matters: A function type can express a relationship that its implementation proves. - Case Splitting Equality Evidence: Trace the implementation of sameS by splitting on its equality evidence and filling the resulting hole.
Why it matters: Case-splitting on evidence lets Idris refine the inputs and reveal the equality still to be proved. - Precise Equality Test Types: Distinguish checkEqNat from == in how their types express the relationship between inputs and output.
Why it matters: A precise type can communicate more about a comparison than a plain equality test.
Key terms: EqNat, sameS, S, proof, case-split, Same, hole, checkEqNat, ==
8.1.5 Implementing exactLength, second attempt
This section implements exactLength using evidence of equal natural numbers to return a vector at the requested length.
- Length comparison with evidence: Explain how exactLength uses checkEqNat to compare the input vector’s length with the requested length, and what it does when they differ.
Why it matters: The comparison supplies the type information needed to justify returning the vector at the requested length. - Equality evidence type refinement: Trace how matching the equality evidence lets exactLength return the input vector at the requested length.
Why it matters: Pattern matching on evidence connects the length check to the type of the returned vector.
Key terms: exactLength, checkEqNat, Maybe, EqNat, Boolean comparison, Same, case-split, type refinement, Vect
8.1.6 Equality in general: the = type
This section introduces Idris’s generic equality type, reflexive equality proofs, and the use of cong to preserve equality through a function.
- Generic equality and reflexivity: Explain how Idris’s built-in equality type and Refl express equality, including how evaluation affects equality expressions.
Why it matters: Generic equality lets you express relationships between values without defining a separate equality type for each data type. - Congruence of equal values: Explain how cong turns an equality into an equality between results of applying the same function, using the successor example.
Why it matters: Congruence lets an existing equality support a new equality involving the same transformation on both sides.
Key terms: generic equality type, =, Refl, reflexive, cong, sameS, implicit function
8.2 Equality in practice: types and reasoning
This section introduces the usefulness of equality proofs when defining functions over dependent types, particularly number-indexed vectors.
- Equality proofs in dependent types: Explain why equality proofs and functions that manipulate them can be useful with dependent types, using natural-number expressions in vector types or the sameS example.
Why it matters: Equality evidence can help connect expressions that appear in dependent types.
Key terms: equality proofs, dependent types, sameS, Vect
8.2.1 Reversing a vector
This section attempts a length-preserving vector reverse and exposes a type mismatch in its recursive case.
- Length-preserving vector reversal: Describe the type and recursive rules for reversing a vector, including how the empty case is implemented.
Why it matters: The length-preserving type gives the implementation a property that Idris must check. - Recursive case type mismatch: Explain the type mismatch encountered when implementing the nonempty reverse case and why it is surprising.
Why it matters: The mismatch shows that an apparently correct length calculation can still prevent the definition from type-checking.
Key terms: Vect, myReverse, case-split, type mismatch, Vect (k + 1), Vect (S k)
8.2.2 Type checking and evaluation
This section explains how type evaluation exposes a vector-length mismatch in myReverse and identifies an equality that can resolve it.
- Type checking by evaluation: Explain how Idris compares an expression’s type with its expected type after evaluation.
Why it matters: This explains why differently written types can sometimes type-check without an explicit equality proof. - Addition with unknown arguments: Explain why 1 + k evaluates to S k while k + 1 remains plus k 1 when k is unknown, and describe how the REPL can reveal this behavior.
Why it matters: The order of arguments can determine whether Idris can evaluate a type involving an unknown value. - Reverse length equality: Describe the length-type mismatch in myReverse and explain how plusCommutative identifies an equality that could be used as a rewrite rule.
Why it matters: Identifying the exact equality needed is the first step toward reconciling the vector result with its required type.
Key terms: type checking, evaluation, expected type, plus, pattern matching, :printdef, anonymous function, myReverse, Vect, plusCommutative
8.2.3 The rewrite construct: rewriting a type using equality
This section uses an equality proof and Idris’s rewrite construct to complete a length-preserving vector reverse.
- Equality rewriting in reverse: Explain how rewrite uses plusCommutative to make the result of myReverse type-check, including how k is brought into scope.
Why it matters: Rewriting lets a type checker use a proven equality to accept a result expressed with an equivalent type. - Proof detail and readability: Describe the readability drawback of the completed myReverse definition.
Why it matters: Keeping computation visible helps readers understand what a verified function does.
Key terms: rewrite, plusCommutative, Vect, equality proofs, proof, result
8.2.4 Delegating proofs and rewriting to holes
This section uses a hole and interactive editing to move the vector reversal length proof into a helper function.
- Hole guided helper extraction: Trace how a hole in myReverse exposes the vector-length mismatch and becomes a helper function.
Why it matters: The hole reveals the precise type correction needed without obscuring the reversal computation. - Separated rewrite proof: Describe how reverseProof uses a rewrite to reconcile the lengths and how the helper is simplified and kept local.
Why it matters: Separating the proof makes the reversal's computation easier to distinguish from the type correction.
Key terms: hole, ?reverseProof, lift, Vect, reverseProof, rewrite, plusCommutative, where
8.2.5 Appending vectors, revisited
This section shows how the order of addition in vector types affects reduction and when equality rewrites are needed.
- Addition order and reduction: Explain why the order of the length arguments in append’s return type determines whether the empty-vector case reduces directly.
Why it matters: The mathematical equivalence of two length expressions does not guarantee that Idris reduces both automatically. - Rewrites for swapped append: Describe why the swapped-length append needs rewrites and how the Prelude’s addition facts and sym support them.
Why it matters: Equality proofs let an implementation type-check even when its length expressions do not reduce directly. - Accumulator based vector reversal: Explain why the exercise’s accumulator-based reverse is an improvement over repeatedly appending a single element.
Why it matters: An accumulator avoids repeated traversal while still requiring the vector lengths to line up in the types.
Key terms: Vect, plus, rewriting, append_nil, append_xs, plusZeroRightNeutral, plusSuccRightSucc, sym, myReverse, reverse'
8.3 The empty type and decidability
This section introduces equality as evidence and the empty type as a way to express impossibility and inequality.
- Equality as evidence: Explain how an equality type guarantees that two values are equal and what Refl contributes to that guarantee.
Why it matters: Equality evidence lets a program rely on a stated relationship between values. - Impossibility and inequality evidence: Explain what evidence of inequality must establish and how a function returning Void expresses impossibility.
Why it matters: Expressing impossibility makes it possible to state guarantees about values not being equal.
Key terms: equality type, =, Refl, Void, empty type, contradiction, x = y
8.3.1 Void: a type with no values
This section uses the empty Void type to express impossibility, demonstrate a negative equality proof, and explain why totality matters.
- Void and impossible inputs: Explain how Void can express that an input or claimed fact is impossible.
Why it matters: Void lets you express what cannot happen as part of a precise program specification. - Impossible equality proof: Describe how the section proves that 2 + 2 cannot equal 5 using an impossible equality pattern.
Why it matters: The example shows how an impossible input can complete a proof without constructing a Void value. - Totality of negative proofs: Explain why a function returning Void must be total to establish that its input is impossible.
Why it matters: Checking totality prevents a looping definition from masquerading as a proof of impossibility. - Elimination of impossible values: State what the Prelude function void expresses about a hypothetical value of Void.
Why it matters: An impossible value can resolve a branch regardless of the result type required.
Key terms: Void, empty type, twoPlusTwoNotFive, Refl, impossible, case split, total function
8.3.2 Decidability: checking properties with precision
This section uses decidable equality for natural numbers to show how Idris can return evidence for both equality and inequality.
- Decidable properties and evidence: Explain decidability and how Dec gives more precise results than Maybe for natural-number equality.
Why it matters: A precise result lets callers use evidence of either outcome, not just a test result. - Natural number equality procedure: Trace how checkEqNat constructs a Dec result for zero and successor cases.
Why it matters: The recursive cases show how an equality test can produce evidence tied to its actual inputs. - Successor inequality contradiction: Explain how noRec proves that unequal predecessors have unequal successors.
Why it matters: This contradiction supplies the evidence required when recursive equality checking finds unequal predecessors.
Key terms: decidability, Dec, Yes, No, Maybe, Void, checkEqNat, Nat, Refl, cong
8.3.3 DecEq: an interface for decidable equality
This section introduces the DecEq interface and its evidence-backed equality test, using vector equality as an exercise.
- Reusable decidable equality interface: Describe how the Prelude’s DecEq interface provides a reusable alternative to type-specific equality checks, including its use in exactLength.
Why it matters: DecEq lets you use the same equality-testing interface across different types. - Evidence from equality tests: Explain what a Yes prf result from decEq guarantees and how that differs from using Boolean equality.
Why it matters: Evidence-backed equality can support guarantees that a Boolean result alone does not provide. - Vector component inequality: Explain what differences between heads or tails imply about the equality of two vectors.
Why it matters: These relationships are useful when reasoning about equality of vectors.
Key terms: DecEq, checkEqNat, exactLength, Prelude, Yes prf, structurally equal, Boolean equality operator, headUnequal, tailUnequal, Vect
8.4 Summary
Where this is used later
- (chapter intro) (chapter 9) · General equality as a type.
- “Snoc” lists: traversing a list in reverse (chapter 10) · The rewrite construct changes a type using equality.
- Removing an element from a Vect: types as contracts (chapter 9) · The empty type has no values.
- Decidable predicates: deciding membership of a vector (chapter 9) · Void as a type with no values
- Generic message-passing processes (chapter 15) · Void is an empty type with no values.
- Membership tests: the Elem predicate (chapter 9) · Checking properties precisely using decidability.
- A predicate for validating user input: ValidInput (chapter 9) · Decidability and evidence for a property's positive or negative outcome.
- Removing an element from a Vect (chapter 9) · DecEq provides decidable equality for the element type.
Concepts explained in this chapter
- equalityThe relation that holds when two values or expressions have the same value.
- VoidAn empty Idris type with no values, commonly used to represent an impossible proposition.
- equality typeAn Idris type whose values witness that two expressions are equal, with Refl witnessing equality of identical expressions.
- DecEqDecEq is the Idris interface for types whose equality can be decided with evidence for either equality or inequality.
- DecDec is an Idris Prelude generic type whose values represent either a proof of a proposition or a proof that the proposition is impossible.
- decidabilityDecidability is the property of a predicate for which an algorithm can determine, for any given input, whether it holds.
- rewritingThe process of replacing an expression with another expression according to a rule.
- appendAppend is an operation in the example list-service interface that requests the concatenation of two lists.
- evaluationThe process of computing the value of an expression by executing its semantics.
- type checkingType checking is the process of verifying that a program satisfies the constraints imposed by its types.
- impossible keywordThe Idris impossible keyword marks a pattern-matching clause whose pattern cannot match a well-typed value.
- mathematical proofA proof is evidence establishing that a proposition is true, represented in Idris by a value whose type expresses that proposition.
- case splittingCase splitting is a development technique that divides an implementation into branches corresponding to the possible forms or values of an expression.
- recursionA technique in which a definition refers to itself to solve a problem through smaller instances of that problem.
- pattern matchingA programming technique that defines behavior by distinguishing values according to their structure or constructor.
- program holeA program hole is a placeholder for an unfinished expression that can be filled in later.
These guides are generated from the text of Manning books by Manning's knowledge graph and link to the sections they draw on. The full books are available on liveBook and at manning.com.
