On Types, Part IV: Simple Enumerations

Before starting to code the module and type system of Babel-17, lets look at a few examples and see if everything works out. Lets first define the type suit:

module com.potsized.card
typedef suit Spades = Spades
typedef suit Hearts = Hearts
typedef suit Diamonds = Diamonds
typedef suit Clubs = Clubs

Somewhere in your code, in order to use the type suit, you would usually first import the module where it is defined:

import com.potsized.card

You could then write code like this:

val x = suit Spades
match x 
  case Spades => "matches Spades"
  case _ => "doesn't match Spades"

The above would evaluate to “matches Spades”. Note that if we would change the first line to

val x = Spades

the whole thing would of course still evaluate to “matches Spades”. The expression

Spades == suit Spades

evaluates to false. The expression

match Spades 
  case Spades : suit => "matches Spades : suit"
  case _ => "doesn't match Spades : suit"

evaluates to “doesn’t match Spades : suit”.

The code for the definition of the type suit is nice and clean, but a little bit verbose. Therefore we introduce two abbreviations. First,

typedef name pattern

is short for

typedef name (x as pattern) = x

where x is supposed to be fresh. Second, several typedefs referring to the same name can be contracted to a single typedef, where the various cases are separated by commas.

Taking both rules together, we can write the typedef for the type suit shorter, like this:

typedef suit Spades, Hearts, Diamonds, Clubs

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: