2 Dynamically-Typed Core
x for a particular object obj, the programmer can declare a field of the following form:
var field x(@obj);
This declaration allocates space for an object reference in the obj object and constructs two real methods attached to the obj object that provide the only access to the variable:
The get accessor method returns the contents of the hidden variable. The set accessor method mutates the contents of the hidden variable to refer to a new object, and returnsmethodx(v@obj) {primrtl { <v.x>} } -- the get accessor methodmethodset_x(v@obj, value) {primrtl { <v.x>:= value; } } -- the set accessor method
void. Accessor methods are specialized on the object containing the variable, thus establishing the link between the accessor methods and the object. For example, sending the x message to the obj object will find and invoke the get accessor method and return the contents of the hidden variable, thus acting like a reference to obj's x instance variable. (Section 5 describes how these accessor methods can be encapsulated within the data abstraction implementation and protected from external manipulation.)To illustrate, the following declarations define a standard list inheritance hierarchy:
Theobjectlistisaordered_collection;methodis_empty(l@list) { l.length = 0 }methodprepend(x, l@list) { -- dispatch on second argumentobject isacons { head := x, tail := l } }objectnilisalist; -- empty listmethodlength(@nil) { 0 }methoddo(@nil, ) {} -- iterating over all elements of the empty list: do nothingmethodpair_do(@nil, , ) {}methodpair_do(, @nil, ) {}methodpair_do(@nil, @nil, ) {}objectconsisalist; -- non-empty listsvar fieldhead(@cons); -- defines head(@cons) and set_head(@cons, ) accessor methodsvar fieldtail(@cons); -- defines tail(@cons) and set_tail(@cons, ) accessor methodsmethodlength(c@cons) { 1 + c.tail.length }methoddo(c@cons, block) { eval(block, c.head); -- call block on head of list do(c.tail, block); } -- recur down tail of listmethodpair_do(c1@cons, c2@cons, block) { eval(block, c1.head, c2.head); pair_do(c1.tail, c2.tail, block); }
cons object has two fields, only accessible through the automatically-generated accessor methods.The syntax of field declarations, excluding static typing aspects and encapsulation, is as follows:
field_decl ::= ["shared"] ["var"] "field" method_name "(" formal ")"
[":=" expr] ";"
Generated with Harlequin WebMaker