8.2. Methods

Methods are functions that are directly associated with a class.

We will create a Lookup method for the Catalog class. This method lets you look up an entry in the catalog by a key associated with the entry. In this example we implement our data as an association list, that is, a list whose elements are also lists, each of which contains exactly two elements : key and value. The library function assoc_equal returns the remainder of the association list starting at the element whose key coincides with the key in the argument of the method Lookup. Thus, Lookup returns the list associated with the key. The special keyword self is used when the instance refers to itself within the function:

method Catalog.Lookup (key)
{
    car(assoc_equal(key, self.data));
}
		

Note that the keyword self can be omitted and the call would look as follows:

    car(assoc_equal(key, .data));
		

The calls to class methods are made by instances, using the dot notation. For example, the instance autoparts created above can call the Lookup method as follows:

Gamma> autoparts.Lookup ("muffler");
nil
		

Since the data attribute did not have a default value, the first time call to Lookup returns nil. In order to put data in the data list, we must create another method:

method Catalog.Add (key, value)
{
    local i;

    if (i = .Lookup (key))
    {
        princ("The entry ", key, " already exists\n");
        nil;
    }
    else
    {
        .data = cons(list(key, value), .data); 
    }
}
	  

Notice that the Add method is using Lookup to determine whether or not the entry already exists in the association list. If so, it returns nil. Otherwise the new entry is added to the data list using the library function cons. The return value of a method is the return value of the last function executed within the body of the method.

Now we can add some data. For example, we can add an entry with the keyword "muffler" and the value 1, which is, for example, the number of mufflers in the stock:

Gamma> autoparts.Add ("muffler", 1);
(("muffler" 1))
Gamma> autoparts.Add ("starter", 5);
(("starter" 5) ("muffler" 1))	    
	  

Now we can look up the entry for a muffler by the keyword:

Gamma> autoparts.Lookup("muffler");
("muffler" 1)
	    

Note that the autoparts instance variables can be queried using the dot notation as follows:

Gamma> autoparts.data;
(("starter" 5) ("muffler" 1))