What is "dependent typing"? Please what is a dependent type, how does it allow a type to depend on a value, provide a conceptual example (e.g., a type for a vector that includes its length), and how can this be used to prove program correctness at compile time.
Assistant
We are going to explain dependent typing in the following steps:
What is dependent typing?
What is a dependent type?
How does it allow a type to depend on a value? (with a conceptual example: vector with length)
How can this be used to prove program correctness at compile time?
Let's break it down.
What is dependent typing?
Dependent typing is a feature of some type systems where types can depend on values. In traditional type systems (like those in Java, C++, or even Haskell without extensions), types are considered to be at a different level from values. For example, the type Int does not depend on any particular integer value. In dependent typing, we can have types that are defined by or that vary according to values.
What is a dependent type?
A dependent type is a type whose definition depends on a value. For instance, we might have a type Vector n where n is a natural number, representing a vector of length n. The type Vector 5 is a vector of length 5, and Vector 10 is a vector of length 10. Here the type Vector is parameterized by a value (the length).
How does it allow a type to depend on a value? (with example)
Let's consider the example of a vector (or array) that includes its length in the type.
In a language with dependent types (like Idris, Agda, or Coq), we might define:
code
data Vector : (n : Nat) -> Type -> Type where
Nil : Vector 0 a
Cons : (x : a) -> (xs : Vector n a) -> Vector (S n) a
Here, Vector is a type constructor that takes two arguments: a natural number n (the length) and a type a (the element type). Then we have two constructors:
Nil is a vector of length 0.
Cons takes an element x and a vector xs of length n, and produces a vector of length S n (where S is the successor function for natural numbers).
So the type of a vector depends on the value of n. For example:
The type Vector 3 Int is a vector of integers of length 3.
This is a simple example. The key point is that the type Vector n is indexed by the value n.
How can this be used to prove program correctness at compile time?
Because the type system can track values (like the length of a vector) in the types, we can write functions that are guaranteed to be correct by construction.
For example, consider a function that appends two vectors. In a language without dependent types, we might have:
code
append : Vector a -> Vector a -> Vector a
But this doesn't guarantee that the result has the length equal to the sum of the two input vectors. With dependent types, we can write:
code
append : (n, m : Nat) -> Vector n a -> Vector m a -> Vector (n + m) a
Now, the type of append says that if we have a vector of length n and a vector of length m, then the result is a vector of length n + m. The type system will check that our implementation of append indeed satisfies this.
How does this prove correctness? Because the type checker verifies that the function's body matches the type. For append, we might implement it by recursion on the first vector:
code
append Z ys = ys
append (S n) xs ys = Cons (head xs) (append n (tail xs) ys)
But note: in a dependently typed language, we have to pattern match on the vector in a way that respects the length. The type checker will ensure that:
In the base case (when the first vector is Nil), the type of ys is Vector m a and we return ys, so the result type is Vector (0 + m) a which is Vector m a (if the type checker knows that 0 + m = m).
In the inductive case, we have a vector xs of type Vector (S n) a and we break it into head and tail (where tail has length n). Then we recursively call append n (tail xs) ys which returns a vector of length n + m. Then we Cons the head, so we get a vector of length S (n + m). But note that the type we need is Vector ((S n) + m) a. The type checker must be able to see that S (n + m) = (S n) + m (which is true for natural numbers). This might require the type checker to know some arithmetic, or we might have to provide a proof that . However, in many dependently typed languages, the equality of these expressions is decidable and can be checked automatically.
Additional note: Difficulty
While dependent types are very powerful, they can make type checking undecidable in general (because we might have to prove arbitrary mathematical theorems). In practice, dependently typed languages use heuristics and require the programmer to provide more annotations or proofs for complex properties. But for many practical cases (like length-indexed vectors), the type checker can handle it automatically.
Let's summarize:
code
Dependent types allow types to be parameterized by values. This enables us to encode more precise invariants in the type system. By writing functions that match these precise types, we are forced to implement them correctly (with respect to those invariants) and the type checker verifies this at compile time. Thus, we can prove certain correctness properties of our programs at compile time.
We have provided a conceptual example with vectors and their lengths, and explained how an append function's type enforces a length invariant.
Note: The example code is in a pseudo-Idris/Agda style.
Excellent question. Let's break down dependent typing step by step, from the fundamental concept to its power for compile-time correctness.
1. What is Dependent Typing?
Dependent typing is a type system feature where types can depend on values (or other types). In conventional type systems (like Java, C++, Haskell), types and values live in separate worlds:
Int, String, List<T> are types
5, "hello", [1,2,3] are values
A type never directly references a specific value. For example, you cannot have a type Array of length 5—you only have Array, and the length is a runtime property.
In dependent type systems, this barrier breaks down: types can be indexed by or defined in terms of values. This allows types to express much richer, value-specific invariants.
2. What is a Dependent Type?
A dependent type is a type whose definition depends on a value. Formally, if T is a type that depends on a value v of type V, we write:
code
T(v) : Type
Here T is a type family (a function from values to types). For a given v, T(v) is a concrete type.
3. How Does It Allow a Type to Depend on a Value? (Conceptual Example)
Example: Length-Indexed Vectors
A vector is a fixed-size array. Its crucial property is its length.
In a non-dependent language (e.g., Haskell without extensions), you might define:
haskell
data Vec a = Nil | Cons a (Vec a) -- length not tracked in type
Here, Vec Int could be a vector of any length. The length is not part of the type—you'd need runtime checks to ensure safe operations like head or zip.
With Dependent Types (e.g., Idris, Agda)
We define a vector type that carries its length in the type:
idris
data Vect : (n : Nat) -> (a : Type) -> Type where
Nil : Vect 0 a
(::) : (x : a) -> (xs : Vect n a) -> Vect (S n) a
-- S n is "successor of n" (i.e., n+1)
Now:
Vect 0 Int is the type of empty integer vectors
Vect 3 String is the type of 3-element string vectors
Vect (2 + 1) Bool is the type of 3-element boolean vectors (the type evaluates 2 + 1 to 3 at compile time).
Key insight: The type Vect n a is indexed by the valuen : Nat. The same type constructor Vect applied to different n yields different, incompatible types.
4. Using Dependent Types to Prove Correctness at Compile Time
Because types now encode precise value-level facts, we can write functions whose types guarantee correct behavior. The type checker then verifies these guarantees at compile time.
Example 1: Safe head (first element) for non-empty vectors
Without dependent types:
haskell
head :: [a] -> a
head [] = error "empty list"
head (x:_) = x
This compiles, but may crash at runtime.
With dependent types:
idris
head : (n : Nat) -> Vect (S n) a -> a
head 0 (x :: xs) = x
Type meaning: "For any natural number n, if you give me a vector of length S n (i.e., at least 1), I return an a."
The pattern (x :: xs) only matches vectors of length S n (non-empty).
There's no case for Nil because Vect 0 a cannot be passed—the type Vect (S n) a excludes empty vectors.
No runtime error possible—the type system guarantees the input is non-empty. Compile-time proof: the function's type is only callable with valid inputs.
Example 2: Append preserves length
Define append (or +++):
idris
append : Vect n a -> Vect m a -> Vect (n + m) a
append Nil ys = ys
append (x :: xs) ys = x :: append xs ys
Type guarantees:
Input: xs : Vect n a, ys : Vect m a
Output: Vect (n + m) a
The output length is statically known as n + m.
The type checker verifies:
Base case: Nil has type Vect 0 a, so ys : Vect m a matches Vect (0 + m) a (reduces to Vect m a).
Inductive case: If xs : Vect n a and recursively append xs ys : Vect (n + m) a, then x :: ... has type Vect (S n + m) a. The type checker must confirm S n + m = S (n + m) (by arithmetic normalization). This may require built-in arithmetic rules or a small proof—but it’s checked at compile time.
Thus, the program cannot incorrectly compute a wrong-length result. If you try to write a buggy append that drops an element, the type checker will reject it because the resulting length wouldn’t match n + m.
Example 3: Proving sorting correctness
You can define:
Sorted : (xs : Vect n Int) -> Type (a predicate that xs is sorted)
Permutation : (xs, ys : Vect n a) -> Type (a predicate that ys is a permutation of xs)
Then give a sort function the type:
idris
sort : (xs : Vect n Int) -> (ys : Vect n Int ** (Sorted ys, Permutation xs ys))
The return type is a dependent pair (Sigma type): a vector ystogether with proofs that ys is sorted and a permutation of xs.
The implementation must construct these proofs (often by recursion and calling lemmas). If you implement a "sort" that doesn’t actually sort, the type checker will reject it because you cannot produce the Sorted proof.
This is proving correctness at compile time: the type checker verifies that sort satisfies its specification.
5. How It Works Under the Hood
Type-level computation: The type system can evaluate expressions (like n + m, S n) during type checking. This is sometimes called type-level functions or type families.
Unification with values: When you call a function, the type checker unifies not just types but also the value indices. E.g., if you have append {n=2} {m=3}, the return type becomes Vect (2 + 3) a → Vect 5 a.
Proofs as values: Proofs of properties (e.g., Sorted xs) are first-class values in the language. They’re often implemented as empty types (data Sorted xs = ...) with no runtime representation—they get erased after compilation (a technique called proof irrelevance).
Total correctness: Many dependently typed languages are total (no infinite loops, no partial functions). This ensures proofs are valid—you can’t have a proof that “diverges” or crashes.
6. Trade-offs and Challenges
Steep learning curve: Writing proofs can be like doing discrete math.
Compilation times: Type checking involves theorem proving (can be slow).
Practicality: Used in critical systems (e.g., aerospace, compilers), verified OS kernels (e.g., seL4), and formalized mathematics (e.g., Univalent Foundations).
Ergonomics: Languages like Idris 2, Agda, Coq, and F* (used by Microsoft for cryptographic protocols) provide tooling to manage complexity.
Summary
Aspect
Conventional Types
Dependent Types
Type dependency
Types independent of values
Types can depend on values
Expressiveness
Can say “this is a list of Int”
Can say “this is a list of Int of length 5”
Safety
Runtime checks for invariants
Compile-time proofs of invariants
Example
head : [a] -> a (may fail)
head : {n : Nat} -> Vect (S n) a -> a (always safe)
Proofs
External (e.g., unit tests)
Embedded in types, checked by compiler
In essence: Dependent types turn the type system into a logic (via Curry-Howard isomorphism), where writing a program of type T is equivalent to constructing a proof that T is true. This allows catching deep logical errors before the program ever runs.
S (n + m) = (S n) + m
So, by writing the function with the dependent type, and having the type checker verify the implementation, we are proving that the function is correct with respect to the length preservation.
This is a simple example. More complex properties can be encoded, such as:
A sorting function that returns a list that is sorted and is a permutation of the input.
A function that operates on binary trees and preserves the tree invariant.
In a dependently typed language, we can state these properties in the types and then the function implementation must construct a value of that type, which is a proof of the property.
However, note that the type checker might not be able to automatically verify all properties. Sometimes we have to provide explicit proofs (which are also values in the language) to convince the type checker. But the key idea is that the type system is expressive enough to encode these correctness properties, and then the act of writing the program and having it type-check is equivalent to constructing a proof of correctness.