Chapter 10. Views: extending pattern matching
In type-driven development, functions are usually shaped by the types of their inputs, and ordinary pattern matching only lets you inspect values according to their constructors. This chapter introduces views as a way to extend that style of matching, letting you describe alternative ways of observing the same data. Instead of being limited to matching lists from the front, you can define views that expose the last element first, split a list into halves, or reveal a data structure through an abstract interface while still supporting pattern matching.
The main technique is to pair a view type with a covering function that builds a view value for a given input, then use the with construct to pattern-match on that intermediate result. The chapter first shows a simple view for matching the end of a list, then uses the same idea to define functions like reverse and merge sort. It also explains why some direct formulations fail: Idris cannot always infer the hidden structure behind expressions like concatenation, and it may reject functions as non-total when recursive calls are made through a view that is rebuilt each time.
To address those limits, the chapter develops recursive views, such as a snoc-list representation and a recursive split view, which preserve the decreasing structure needed for totality checking and avoid rebuilding views on each recursive call. These recursive views make it possible to write efficient, total traversals that operate from the end of a list, compare suffixes, or sort by repeatedly splitting and merging. The final part applies the same idea to data abstraction: a store is hidden behind a module interface, while a view exposes its contents in a safe, pattern-matchable form, showing how views can support both efficient computation and clean encapsulation.
Summary
- A view is a dependent type that describes the possible forms of another data type. Views take advantage of dependent pattern matching to allow you to extend the forms of patterns you can use.
- A covering function builds a view of a value. By convention, its name is the name of the view with an initial lowercase letter.
- The with construct allows you to use views directly, without defining an intermediate function.
- You can use views to define alternative traversals of data structures, such as extracting the last element of a list instead of the first.
- Recursive views help you write functions that are guaranteed to terminate, by writing recursive functions that pattern-match on the view.
- Idris provides several views for alternative traversals of List in the Data.List.Views library. Similar libraries exist for Vect, Nat, and String.
- You can hide the structure of data in a module, while still supporting interactive type-driven programming with that data, by exporting views for traversing data structures.
Type-Driven Development with Idris ebook for free