An ocaml program can declare new types using the type
declaration:
type
name
=
type-expr
So far we’ve seen:
type 'a pair = 'a * 'a
type student = { name: string; id : string}
type size = Small | Medium | Large | XLarge
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:
<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:
Inductive cases:
Define functions to:
cs2041.org