CSCI 2041

ADVANCED PROGRAMMING PRINCIPLES

Type unions: recursive data types

Type declarations

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

Recursive Unions

type 'a mystery =
  Foo | Bar of 'a * 'a mystery

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…

COMPUTING WITH RECURSIVE TYPES

We’ve already seen lists:

type 'a list = [] | (::) of 'a * 'a list

Another basic structure is binary trees:

type 'a btree = Empty
  | Node of 'a * 'a btree * 'a btree

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…

let leaf x = Node (x,Empty,Empty)

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 =

Type Union Summary

type ('n1,...,'n𝓀) tname =
  Name1 of τ1 |
  Name2 of τ2 | ...

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.

Example

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

// reveal.js plugins