On Types, Part II

After having established where types live (they live in modules) it is time to look closer at how the definition of a new type might look like. Previously, we denoted the introduction of a new type for pokercards like this:

typedef pokercard

This introduces a new pattern : pokercard which can be used to test if something has type pokercard. It can be used like this:

match v
  case 10 => ...
  case Cool u => ...
  case pc : pokercard => ...
  ...
end

Just like any other pattern, it can also be used in function definitions:

def allInOdds(card1 : pokercard, card2 : pokercard) = ...

Note that this way, you can annotate the types of the arguments of the function, but not the return type of a function. If you also want to restrict the return type of a function, you do it like this:

def allInOdds (card1 : pokercard, card2 : pokercard) : real = ...

The semantics of this is that whenever the return value of that branch of allInOdds is neither a real nor an exception, then a TypeError exception is thrown.

How do you generate values of type pokercard in the first place? The answer to this is the operator :> which can be used to turn any value into a value of a given type. For example,

Ace :> pokercard

is a pokercard with inner value Ace. Now, the thing about inner values is that they are not visible or detectable except in three ways. First, if the inner value is a user-defined object, then messages to the value are routed to the inner value. Second, in the same scope in which the type has been defined you can use :> as a pattern construct to see the inner value. Third, the order among the values of a given type is established according to the order of the inner values.

Advertisements

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s


%d bloggers like this: