# Data Types¶

## Review so far¶

We’ve seen some base types and values: int, string, etc.

## Next: Building datatypes¶

Three key ways to build complex types/values

“Each-of” types

Value of T contains value of T1 and a value of T2

Example: a pair (int * int)

“One-of” types

Value of T contains value of T1 or a value of T2

Example: Value is an int or null

Recursive

Value of T contains (sub)-value of same type T

Example: a list

## Defining a One-of Data Type¶

An example of creating a One-of Data Type:

(* DataTypes *)

type attrib =
| Name     of string
| Age      of int
| DOB      of int * int * int
| Address  of string
| Height   of float
| Alive    of bool
| Email    of string


Creating a value with a “label” Name:

# let a1 = Name "Bob";;
val a1 : attrib = Name "Bob"


Above, we’ve created a value of type attr. Below, we create a value with a “label :code:”Age”:

# let a2 = Age 22;;
val a2 : attrib = Age 22


Both a1 and a2: are of type attrib. Thus, we can put them in a list!:

# let a_1 = [a1, a2];;


Note

Defining another type with a “label” Name will overshadow the label Name of the type attrib

## Data Types & Pattern-Matching¶

### Using Match with “labels”¶

Here’s how to match a value with “labels”:

let a1 = (Alive false)
match a1 with
| Name s -> 0
| Age i -> i
| _ -> 10;;


Note

In the above example, as a side-effect, we’ve also created a the variables s and i.

### The when clause¶

The when {condition} clause is a pattern-matching keyword that requires that {condition} is true for the corresponding pattern to match.

 let a1 = (Alive false)
match a1 with
| Name s -> 0
| Age i when i < 10 -> i
| _ -> 10;;


Note

The above two examples will yield a Warning 8 since the pattern-matching is not exhaustive; e.g., the label Email would not be caught.

### Adding a “label” that has no type¶

This is how the type bool is internally defined:

type bool =
| True
| False


Now we can match as so:

match _ with
| True -> ...
| False -> ...


Now we can set a value to our custom bool:

let var = True


## Recursive Type Primer¶

An ordered sequence of integers::
type MyIntList =
Nil
NonNil of int * MyIntList