Chapter 2. Basic types

 

This chapter covers

  • Common primitive types and their uses
  • How Boolean expressions are evaluated
  • Pitfalls of numerical types and text encoding
  • Fundamental types for building data structures

Computers represent data internally as sequences of bits. Types give meaning to these sequences. At the same time, types restrict the range of possible values any piece of data can take. Type systems provide a set of primitive or built-in types and a set of rules for combining these types.

In this chapter we will look at some of the commonly available primitive types (empty, unit, Booleans, numbers, strings, arrays, and references), their uses, and common pitfalls to be aware of. Although we use primitive types every day, each comes with subtle nuances we must be aware of to use them effectively. Boolean expressions can be short-circuited, for example, and numerical expressions can overflow.

We’ll start with some of the simplest types, which carry little or no information, and move on to types that represent data via various encodings. Finally, we’ll look at arrays and references, which are building blocks for all other more-complex data structures.

2.1. Designing functions that don’t return values

Viewing types as sets of possible values, you may wonder whether there is a type to represent the empty set. The empty set has no elements, so this would be a type for which we can never create an instance. Would such a type be useful?

2.1.1. The empty type

2.2. Boolean logic and short circuits

2.3. Common pitfalls of numerical types

2.4. Encoding text

2.5. Building data structures with arrays and references

Summary

Answers to exercises

sitemap