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


Dictionary Protocol

Dictionary is a subprotocol of collection and keyed-sequence. A dictionary has a series of elements identified by unique keys. Keys are compared with the = function. This is an abstraction of an association list or a hash table.

The following method requirements, in addition to the collection and keyed-sequence functions, constitute the dictionary protocol:

defprotocol dictionary is collection, keyed-sequence
  (x is dictionary)[key]                        ; error if not present
  (x is dictionary)[key, key: default]          ; return default if not present
  contains?(x is dictionary, key) is boolean
  any?(function is function, x is dictionary, rest: more is dictionary) is boolean
  every?(function is function, x is dictionary, rest: more is dictionary) is boolean
  map(function is function, x is dictionary, rest: more is dictionary)
  reduce(function is function, initial-value, x is dictionary, rest: more is dictionary)
  reduce-right(function is function, initial-value, x is dictionary, rest: more is dictionary)

Many dictionaries also implement assignable-sequence and add the method requirement:

defprotocol assignable-dictionary is dictionary, assignable-sequence
  (x is dictionary)[key] := new-element

The dictionary function is a pseudo-constructor that constructs an instance of a default dictionary implementation class. Its arguments are alternating keys and elements.

The dictionary# function is a pseudo-constructor that constructs an instance of a default dictionary implementation class. Its argument is the initial capacity of the dictionary (expected number of elements).

When the functions any?, every?, map, reduce, and reduce-right are called with a dictionary as their first collection argument, they iterate over that dictionary and use its keys to lookup elements in the rest of the dictionaries. If a key is not present in one of the rest of the dictionaries, false is used as the default element value. The iteration stops when the first dictionary is exhausted. The lengths of the more dictionaries don't matter. This is conceptually compatible with their behavior on collections that are not dictionaries but not identical.

When map is called with a dictionary as its first collection argument, the result is a dictionary of the same type with the same keys.


Previous page   Table of Contents   Next page