05 More On Types
05 More On Types
Programming Abstractions
• Primitive types are the basic building blocks for other data types.
Almost all languages Most languages Integers are Since these types
support integer and follow the IEEE- (usually) fixed- have fixed-
floating-point (with 754 standard for precision as well. precision,
various precisions) the definition of •but there is no •only a finite range
numeric types. precision: IEEE standard for of values can be
•a single precision this, since the represented.
floating-point is universal way to
defined with a 24- represent an
bit precision integer is to use
the two’s
• Array
• Set
• List
• Unlike records, which group related fields of disparate types, arrays are
usually homogeneous. Semantically, they can be thought of as a mapping
from an index type to a component or element type.
• But the data type of each array element can, once again, be an array! So we
can have multi-dimensional arrays.
Arrays
• Used to build records or linked data structures like lists and trees.
Even intuitively, we can think of these structures as recursive. For example, an
OCaml list can be defined* as
type 'a list = [] | :: of 'a * 'a list
Uninterpreted types
•
Consist of sets of simple, unstructured values (e.g., integer, boolean), together
with a set of operations to manipulate these values.
• To understand the overall theory of data types, it is also useful to think
that a language comes with a set of uninterpreted (or unknown)
types, with no corresponding operations at all.
In an abstract sense (e.g., in λ-calculus), we can think of the set of uninterpreted
types as a placeholder for the base types.
When we speak of a particular programming language, we will usually no longer
need this abstraction because we can directly deal with the base types of that
language.
But … uninterpreted types are not useless! Even though we cannot name its
elements directly, we can still bind variables. For example:
(* repeat g : 'a -> 'a twice, where the argument’s type is unknown *)
fun: (g x) -> g (g x)
Algebraic data types
• Programs often need to deal with collections of values (often heterogeneous).
A tree is either empty, or a node with children where each child is, again, a tree.
A list is either nil (i.e., []) or a cons (i.e., :: ) with a head and a tail.
• The theoretical mechanism that supports this is called algebraic data types.
* Source: https://ocaml.org/learn/tutorials/data_types_and_matching.html#Variants-qualified-unions-and-enums
Unions • The equivalent in OCaml is just the record type we have
seen before.
It is ‘safe’ to access, unlike the union type in C.
The definition is much more concise.
Uses the same pattern matching template.
# type foo =
| Nothing
| Int of int
| Pair of int * int
| String of string;;
type foo = Nothing | Int of int | Pair of int *
int | String of string