An ocaml program can declare new types using the `type`

declaration:

`type`

`name`

`=`

`type-expr`

So far we’ve seen:

- Existing type, new name:
`type 'a pair = 'a * 'a`

- Record types:
`type student = { name: string; id : string}`

- Enumerated union:
`type size = Small | Medium | Large | XLarge`

- Disjoint unions:
`type comment = Like | Rating of int | Coment of string`

What type have we seen that looks like this?

Notice that this type is *recursive*. Lots of interesting problems involve recursive or hierarchical data:

- A binary tree is either a leaf or has two binary trees as children
- A facebook, instagram, twitter, etc. user has a list of followers (users)
- An HTML
*entity*is a`<tag>`

that contains a sequence of HTML entities…

We’ve already seen lists:

Another basic structure is binary trees:

Common aspects of both:

“base case(s)” in the type definition

“recursive case(s)” in the type definition

Let’s see some examples of binary trees…

Recursive computations on binary trees:

`let rec depth =`

`function`

`| Empty -> 0`

`| Node (_,l,r) -> 1 + (max (depth l) (depth r))`

`let rec sum_tree : int btree -> int =`

Each `τ𝒾`

is a type expression that may reference the type variables `'n1, ..., 'n𝓀`

.

If type variables are used, `tname`

becomes a new type constructor.

Each `Name𝒾`

becomes a (possibly polymorphic) new value constructor.

Define an inductive type for boolean expressions:

Base case:

- a constant (true or false)

Inductive cases:

- negation of an expression
- AND of two expressions
- OR of two expressions

Define functions to:

- evaluate a boolean expression
- decide if an expression is (syntactically) monotone

`cs2041.org`