Programming Language for Old Timers


by David A. Moon
February 2006 .. September 2008

Comments and criticisms to dave underscore moon atsign alum dot mit dot edu.


Previous page   Table of Contents   Next page


Protocol Definition

A protocol is simply a named type. Its semantics, if any, comes from the methods and method requirements that have parameters of that type.

A method requirement is like a method definition with no body. It asserts that when the function is called with arguments of the specified number and types, there will be an applicable method (not necessarily always the same method). If a method requirement specifies a result type or types, the applicable method must declare result type(s) that are the same or subtypes. This is useful documentation of the intended meaning of a function.

If a compiler can infer that this assertion can be unsatisfied, it should issue a warning that a method that is intended to be available is known to be missing. This is a warning, not an error, because the missing method could always be dynamically created before it is needed.

Typically some of the parameter types of a method requirement are protocols, although this is not required.

If a parameter type in a method requirement is something, that parameter type is disregarded when checking whether there is a method that satisfies the method requirement. There are no objects that are members of something. The difference between something and anything is that something requires a method to exist that is applicable to some object in that argument position, while anything requires a method to exist that is applicable to every object in that argument position.

A result type in a method requirement cannot usefully be something since that type has no subtypes.

For convenience, a single defprotocol statement can both define a protocol type and specify a series of method requirements. It is good practice, but not required, for each method requirement to have at least one parameter or result that is restricted to the protocol type.

The syntax of the defprotocol statement is:

defmacro defprotocol ?:name [ ?=is { ?superprotocol is name & ~^ , }+ ]
                     { ^ ?:method-head }* => ...

Example:

defprotocol sequence
  start-iteration(x is sequence, result: state is anything)
  end?(x is sequence, state is something, result: end? is boolean)
  next(x is sequence, state is something, result: element)
  advance(x is sequence, state is something, result: new-state)

The syntax of the require statement is:

defmacro require ?:method-head => ...

Example of a standalone method requirement: suppose every object were required to have a to-string method, but there is no default method specialized to anything. This can be asserted by:

require to-string(x is anything, result: string)


Previous page   Table of Contents   Next page