Chapter 6: Chapter 6. Programming with first-class types
This introduction explains first-class types in Idris and illustrates calculating types from data.
After this chapter you will be able to
- First-class types in Idris. Explain what it means for types to be first-class in Idris, using a vector’s length as an example of information stored in a type.
- Types calculated from data. Describe how a function’s type can be calculated from other data, using printf’s format string as an example.
- Types and expressions. Explain how types and expressions share a language in Idris, using vector append as an example.
- Purposes of calculated types. Distinguish type synonyms from type-level functions that calculate a type from contextual input, using the section's examples.
- Type synonyms as functions. Explain how ordinary functions can provide informative names for types, using Position and Polygon as examples.
- Type-level function behavior. Explain what a type-level function is in Idris and how pattern matching can be used to calculate a type.
- Dependent return type refinement. Trace how case splitting refines the return type of getStringOrInt and permits a different result in each Boolean case.
- Dependent argument type refinement. Explain dependent pattern matching using valToString, including how splitting on the flag refines the other argument and determines its conversion.
- Case expressions in types. Explain how the case expression in valToString calculates the type of its second argument from isInt, and how the definition handles each branch.
- Incremental type hole refinement. Trace how holes and case splitting let the author develop valToString before its complete argument type is known.
- Input-dependent function types. Explain how a type-level function can give a function a variable number of arguments with types determined by an input value.
- Computed variable argument types. Explain how AdderType calculates the type of adder from the number of additional arguments, and describe what adder does with those arguments.
- Accumulator recursion and refinement. Trace the case-split implementation of adder, including what the successor-case hole reveals and how the accumulator is updated.
- Format Driven Argument Types. Explain how a printf format string determines the number and types of its arguments and the resulting output.
- Intermediate Format Representation. Describe how Format represents a format string and why it is used as an intermediate type.
- Printf Construction Pipeline. Describe how the printf implementation uses Format, PrintfType, and a helper to produce its result.
- Data store schema meaning. Explain how a schema describes the form of data in a store, contrasting the original String-only store with a store containing more complex entries.
- Schema based DataStore refinement. Explain why DataStore stores a Schema description and uses SchemaType to translate it into a concrete entry type.
- Record declarations and projections. Explain how an Idris record declaration defines a data type and provides field projections, using DataStore as an example.
- Schema dependent item projection. Explain why projecting items from the updated DataStore also requires a way to project its schema.
- Incremental Type Error Repair. Describe how to restore type-checking after changing DataStore without completing every definition immediately.
- Schema Aware Store Updates. Explain why addToStore needs changes when DataStore gains a schema.
- Schema Aware Command Parsing. Explain how refining Command moves input validation earlier, and why the temporary parsing hole remains incomplete.
- Schema-driven type refinement. Explain how bringing the implicit schema into scope and case-splitting on it reveals the type of item in each display branch.
- Recursive entry rendering. Describe how the display branches convert simple entries and recursively render composite entries.
- Schema parsing and failure. Explain how parseBySchema uses an explicit schema to determine the result type and how parsing failure is reported to parseCommand.
- Prefix and complete parsing. Distinguish the roles of parsePrefix and parseBySchema in parsing an entire input.
- Basic schema prefix parsing. Describe how the parser handles integer and string schema prefixes.
- Composite schema recursive parsing. Trace how parsePrefix handles a composite schema by parsing its two parts in sequence.
- User-defined schema command. Describe how a user can set a schema without changing and recompiling main, including how the command is parsed.
- Empty-store schema changes. Explain why the implementation permits a schema change only when the store is empty, and identify the alternative design mentioned.
- Schema-guided input types. Explain how the schema description guides input parsing and prevents invalid entries from being added.
- Maybe computation sequencing. Explain how (>>=) captures the common pattern of passing successful Maybe results onward while propagating failure, using maybeAdd or parseCommand as an example.
- Do notation for Maybe. Describe how do notation expresses Maybe sequencing through (>>=), and how it simplifies the schema-parsing case.
What it builds on
- First-class types (chapter 1) · The earlier introduction to first-class types.
- Adding precision to types: working with vectors (chapter 3) · Vectors whose types include their lengths.
- Defining vectors (chapter 4) · Vectors use a length in their type.
- Defining functions by pattern matching (chapter 3) · Defining functions by pattern matching and inspecting cases.
- Incomplete definitions: working with holes (chapter 1) · Working with holes in incomplete definitions.
- Type-directed search: automatic refining (chapter 3) · Hole types can guide interactive refinement.
- Writing generic functions with constrained types (chapter 2) · Generic functions can constrain the types they accept.
- Commands: parsing user input (chapter 4) · Separating parsing from processing when handling data-store commands.
Section by section
Introduction
This introduction explains first-class types in Idris and illustrates calculating types from data.
- First-class types in Idris: Explain what it means for types to be first-class in Idris, using a vector’s length as an example of information stored in a type.
Why it matters: Treating types as first-class lets a type express information about the data it describes. - Types calculated from data: Describe how a function’s type can be calculated from other data, using printf’s format string as an example.
Why it matters: Calculating types from data lets function requirements reflect the data they work with.
Key terms: first-class, types, expressions, vector, type-level functions, printf, format string, arguments
6.1 Type-level functions: calculating types
This section introduces types and expressions as part of the same language and explains why functions can calculate types.
- Types and expressions: Explain how types and expressions share a language in Idris, using vector append as an example.
Why it matters: This shared language makes it possible to compute and use types within ordinary Idris programs. - Purposes of calculated types: Distinguish type synonyms from type-level functions that calculate a type from contextual input, using the section's examples.
Why it matters: Calculating types can make code clearer and let types reflect the context in which values are used.
Key terms: Vect, Nat, expressions, types, type synonyms, type-level functions, Position, schema
6.1.1 Type synonyms: giving informative names to complex types
This section introduces type synonyms as ordinary functions that give informative names to types and shows how Idris tools work with them.
- Type synonyms as functions: Explain how ordinary functions can provide informative names for types, using Position and Polygon as examples.
Why it matters: Meaningful type names communicate the purpose of data without changing its underlying representation. - Tool treatment of synonyms: Describe how REPL evaluation and expression search handle the type synonyms in the polygon example.
Why it matters: You can use informative type names without preventing interactive tools from working with their underlying types.
Key terms: type synonym, Position, Polygon, Type, REPL, expression search, type synonyms
6.1.2 Type-level functions with pattern matching
This section uses pattern matching on a Boolean to calculate types and refine dependent function inputs and outputs.
- Type-level function behavior: Explain what a type-level function is in Idris and how pattern matching can be used to calculate a type.
Why it matters: This lets you calculate types using familiar Idris programming constructs. - Dependent return type refinement: Trace how case splitting refines the return type of getStringOrInt and permits a different result in each Boolean case.
Why it matters: Case splitting turns a calculated return type into a concrete requirement for each branch. - Dependent argument type refinement: Explain dependent pattern matching using valToString, including how splitting on the flag refines the other argument and determines its conversion.
Why it matters: Inspecting one input can reveal the type of another, allowing each case to use the appropriate operation.
Key terms: type-level functions, Type, case splitting, getStringOrInt, StringOrInt, refined type, dependent pattern matching, valToString, trim, cast
6.1.3 Using case expressions in types
This section develops valToString using a case expression in its type and holes to refine the definition interactively.
- Case expressions in types: Explain how the case expression in valToString calculates the type of its second argument from isInt, and how the definition handles each branch.
Why it matters: A case expression lets a function specify an argument type that depends directly on an earlier value. - Incremental type hole refinement: Trace how holes and case splitting let the author develop valToString before its complete argument type is known.
Why it matters: Holes let you make progress on a definition while discovering the type it needs.
Key terms: case expression, type level, valToString, isInt, hole, case splitting, refine, ?argType
6.2 Defining functions with variable numbers of arguments
This section introduces using type-level functions to give functions argument lists that depend on an input value.
- Input-dependent function types: Explain how a type-level function can give a function a variable number of arguments with types determined by an input value.
Why it matters: This lets a function’s type describe its argument list more precisely than a generic variable-length argument list.
Key terms: type-level functions, function types, variable-length argument lists
6.2.1 An addition function
This section develops a variable-argument addition function using a computed type and refines it to work with any numeric type.
- Computed variable argument types: Explain how AdderType calculates the type of adder from the number of additional arguments, and describe what adder does with those arguments.
Why it matters: Computing a type from an input lets a function accept a variable number of arguments while retaining a precise type. - Accumulator recursion and refinement: Trace the case-split implementation of adder, including what the successor-case hole reveals and how the accumulator is updated.
Why it matters: The refined hole type guides both the function you must return and the recursive call that completes it. - Generic numeric adder: Describe how the adder is refined to work with numeric types other than Int.
Why it matters: This refinement makes the same variable-argument pattern usable with different numeric types.
Key terms: AdderType, type-level function, Nat, numargs, accumulator, case splitting, Z, S k, hole, recursive call
6.2.2 Formatted output: a type-safe printf function
This section develops a type-safe printf whose format string determines its argument types and whose result is a String.
- Format Driven Argument Types: Explain how a printf format string determines the number and types of its arguments and the resulting output.
Why it matters: The format determines what arguments are valid before the formatted string is built. - Intermediate Format Representation: Describe how Format represents a format string and why it is used as an intermediate type.
Why it matters: An intermediate representation lets the program work with the structure of a format separately from reading its text. - Printf Construction Pipeline: Describe how the printf implementation uses Format, PrintfType, and a helper to produce its result.
Why it matters: The implementation connects the calculated function type to the actual construction of the formatted result.
Key terms: printf, format string, directive, Int, String, Format, Str, Lit, Number, End
6.3 Enhancing the interactive data store with schemas
Introduces schemas as descriptions of data-store entry types and previews the planned extension of the existing store.
- Data store schema meaning: Explain how a schema describes the form of data in a store, contrasting the original String-only store with a store containing more complex entries.
Why it matters: Schemas let a store describe entries with different structures rather than only strings.
Key terms: schema, DataStore, String
6.3.1 Refining the DataStore type
This section refines DataStore to describe user-selected entry structures with schemas and explains how to declare operator fixity.
- Schema based DataStore refinement: Explain why DataStore stores a Schema description and uses SchemaType to translate it into a concrete entry type.
Why it matters: This design lets the store describe user-selected entry structures instead of restricting every entry to a String. - Operator fixity and precedence: Describe how Idris declares an operator's associativity and precedence, including the right-associative level-5 declaration used for the schema operator.
Why it matters: Fixity declarations specify how an operator groups with other operators. - Temporary Code Commenting: Describe how and why to comment out the rest of the program while refining DataStore.
Why it matters: Temporarily setting aside broken code lets you focus on finishing the revised type.
Key terms: DataStore, Schema, SchemaType, type-level function, fixity, precedence, infixl, infixr, infix, commenting out
6.3.2 Using a record for the DataStore
This section introduces Idris records as a way to define DataStore with automatically generated field projections.
- Record declarations and projections: Explain how an Idris record declaration defines a data type and provides field projections, using DataStore as an example.
Why it matters: Records reduce repetitive code when you need to extract fields from a data structure. - Schema dependent item projection: Explain why projecting items from the updated DataStore also requires a way to project its schema.
Why it matters: The schema determines the type you must use when accessing stored items.
Key terms: record declaration, constructor, projection functions, fields, DataStore, schema, items, projection
6.3.3 Correcting compilation errors using holes
This section repairs the data store program after introducing schemas, using type errors and temporary holes to guide the changes.
- Incremental Type Error Repair: Describe how to restore type-checking after changing DataStore without completing every definition immediately.
Why it matters: This approach lets you regain type-checking while keeping unfinished work visible. - Schema Aware Store Updates: Explain why addToStore needs changes when DataStore gains a schema.
Why it matters: The constructor and insertion functions must agree with the refined store representation. - Displaying Schema Typed Entries: Explain how a hole temporarily repairs getEntry after the store's item type changes.
Why it matters: The hole makes the missing display conversion explicit while allowing getEntry to type-check. - Schema Aware Command Parsing: Explain how refining Command moves input validation earlier, and why the temporary parsing hole remains incomplete.
Why it matters: A more precise command type puts validation at the boundary instead of passing raw input deeper into the program.
Key terms: type errors, holes, type-checks, MkData, schema, addToStore, addToData, getEntry, index, SchemaType
6.3.4 Displaying entries in the store
This section implements a generic display function that converts schema-typed store entries to strings by splitting on the schema.
- Generic display function type: Explain why display can be given the generic type SchemaType schema -> String instead of a type tied to a particular store.
Why it matters: A generic display function avoids tying the conversion to one store. - Schema-driven type refinement: Explain how bringing the implicit schema into scope and case-splitting on it reveals the type of item in each display branch.
Why it matters: Splitting on the schema tells you what data each branch must handle. - Recursive entry rendering: Describe how the display branches convert simple entries and recursively render composite entries.
Why it matters: This completes the conversion for both simple and structured store entries.
Key terms: display, SchemaType, schema, implicit argument, case splitting, SString, SInt, show, case-split, recursively
6.3.5 Parsing entries according to the schema
This section develops a schema-directed parser that converts complete user inputs into appropriately typed values and reports failures.
- Schema parsing and failure: Explain how parseBySchema uses an explicit schema to determine the result type and how parsing failure is reported to parseCommand.
Why it matters: The result type connects each parsed value to its schema while making invalid input explicit. - Prefix and complete parsing: Distinguish the roles of parsePrefix and parseBySchema in parsing an entire input.
Why it matters: Keeping the remainder lets the parser handle parts of a schema while still rejecting incomplete consumption of a whole input. - Basic schema prefix parsing: Describe how the parser handles integer and string schema prefixes.
Why it matters: These cases show how individual schema forms determine what input to consume and what value to produce. - Composite schema recursive parsing: Trace how parsePrefix handles a composite schema by parsing its two parts in sequence.
Why it matters: Sequential recursion lets a schema describe structured entries without losing track of the unconsumed input. - Hole guided parser development: Describe how case splitting, hole types, and reloading guide the development of parsePrefix.
Why it matters: The type-directed workflow makes each parser case smaller and checks intermediate progress.
Key terms: parseBySchema, SchemaType, Maybe, parseCommand, Nothing, parsePrefix, schema, remainder, SInt, SString
6.3.6 Updating the schema
This section adds user-configurable schemas to the data store and explains how schema-dependent types protect its contents.
- User-defined schema command: Describe how a user can set a schema without changing and recompiling main, including how the command is parsed.
Why it matters: This command lets users configure the store while the program is running. - Empty-store schema changes: Explain why the implementation permits a schema change only when the store is empty, and identify the alternative design mentioned.
Why it matters: The restriction prevents a new schema from making existing entries inconsistent with the store's type. - Schema-guided input types: Explain how the schema description guides input parsing and prevents invalid entries from being added.
Why it matters: The schema connects input parsing to the types that keep stored entries valid.
Key terms: schema, SetSchema, Command, parseCommand, processInput, DataStore, empty store, parser, data type, types of the operations
6.3.7 Sequencing expressions with Maybe using do notation
This section explains how Maybe computations can be sequenced using bind and do notation instead of nested case expressions.
- Maybe computation sequencing: Explain how (>>=) captures the common pattern of passing successful Maybe results onward while propagating failure, using maybeAdd or parseCommand as an example.
Why it matters: This pattern lets you combine operations that may fail without repeatedly writing case expressions. - Do notation for Maybe: Describe how do notation expresses Maybe sequencing through (>>=), and how it simplifies the schema-parsing case.
Why it matters: Do notation makes sequences of potentially failing operations easier to read.
Key terms: Maybe, Nothing, Just, (>>=), maybeAdd, do notation, parseCommand
6.4 Summary
Where this is used later
- (chapter intro) (chapter 8) · Functions can calculate types using first-class types.
- Constrained implementations (chapter 7) · Type synonyms
- Digression: modules in Idris (chapter 10) · Type synonyms
- Complex state: defining nested records (chapter 12) · The discussion of nested records builds on records and their fields.
- The data store, revisited (chapter 10) · The earlier DataStore record representation
- A complete program with state: working with records (chapter 12) · Using a record to represent the data store.
- Generic do notation using Monad and Applicative (chapter 7) · Generalizes sequencing and do notation across contexts
- Extending do notation for InfIO (chapter 11) · Using do notation with Maybe
Concepts explained in this chapter
- type-level functionA function whose input and output are evaluated or interpreted in type positions to determine types.
- parsingThe process of converting textual input into a structured representation according to a grammar or format.
- prefix parsingPrefix parsing interprets the beginning of an input while preserving the unparsed remainder.
- dependent pattern matchingDependent pattern matching is pattern matching in which matching a value can reveal information about the types or forms of related values.
- do notationIdris syntax for writing sequences of effectful computations in a more readable form than explicit use of the bind operator.
- type aliasA type synonym is an alternative name for an existing type, often chosen to make the type's meaning clearer.
- variadic argumentsA facility for passing a variable number of arguments to a function, without necessarily encoding their count in the types.
- program holeA program hole is a placeholder for an unfinished expression that can be filled in later.
- bind operatorThe Idris Prelude operator >>= sequences computations by passing the result of one computation to a function that produces the next.
- case statementAn expression that evaluates a value and selects a result by matching it against alternatives.
- projection functionA function generated for a record field that retrieves that field’s value from a record.
- case splittingCase splitting is a development technique that divides an implementation into branches corresponding to the possible forms or values of an expression.
- first-class typeA first-class type is a type that can be manipulated as a language-level value rather than serving only as a static annotation.
- recursionA technique in which a definition refers to itself to solve a problem through smaller instances of that problem.
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.
