HoldFastPlayground

Dependent types by example

A dependent type can mention a value. Pairing a vector of three natural numbers (Vec<Nat, 3>) with an index below three (Fin<3>) rules out out-of-bounds lookups during type checking.

Length-indexed vectors and bounded indices

Vec<T, n> takes an element type and a natural length. VNil<T>() is empty. VCons prepends an element and adds one to the length. At requires a Fin index with that length as its bound.

HoldFast
module SafeLookup;

public definition Vec<Nat, 3> Samples() =>
    VCons(10, VCons(20, VCons(30, VNil<Nat>())));

public definition Nat Read(Fin<3> index) => At(Samples(), index);

public definition Nat Second() => Read(FSucc(FZero<1>()));

FZero<k>() is zero in Fin<k + 1>. FSucc advances both the index and bound. In Second(), it turns zero in Fin<2> into one in Fin<3>. See the same encoding in the Idris tutorial on indexed types.

Try a valid index and a mismatched bound

Open the indexed vectors example. In Console, enter an expression, set Result type to Nat, and select Run. You can also select a suggested expression to run it immediately.

Expression Result
Read(FZero<2>()) 10 at index zero in Fin<3>.
Second() 20 at index one in Fin<3>.
Read(FSucc(FSucc(FZero<0>()))) 30 at index two in Fin<3>.
Read(FZero<3>()) Refused. The argument has type Fin<4>, and Read requires Fin<3> even when the index value is zero.

For an external index, check that it is below n before constructing a Fin<n> for use with At on a Vec<T, n>.

Dependent functions preserve relationships

Copy preserves the length for every input. The type checker infers it from the argument. Dependent functions example

HoldFast
public definition Vec<TElement, length>
    Copy<TElement, ghost Nat length>(Vec<TElement, length> values) => values;

The example also passes length explicitly to a function whose next argument depends on it. In the local Playground, load Dependent functions & length proofs. Change length: 1 to length: 2 in Preserved() and select Compile. Problems reports that the argument has one element where the call expects two. Launch the local Playground

What the type tells you about the program

Copy's signature fixes the output length. A function with that signature could reorder the elements. For this one-element example, SameValue also proves that the returned element is 42. Run PreservedValue() in the browser to see the value, or compile locally and replay the proof in Rocq. Follow the program verification example through Rocq.

Graded types specify input usage. Borrow checking tracks access to owned storage. The HoldFast elaborator guide covers supported indexed data, dependent functions and proof terms.