Base Language: Object-Oriented Programming with Effect and Termination Guarantees


The Pair class can be used to represent linked lists. It shows how classes are defined, and we use it to demonstrate the guaranteed termination of routines.

Local fields are declared via def-fields. A constructor is defined called initialize-with with 2 formal parameters called initial-car and initial-cdr that will initialize the fields of a new pair. Routines are defined via def-routine, such as the routines called first and second with no arguments which are "getters" for the car and cdr field. Two methods are defined called set-first! and set-second! which are setters for these fields. Finally, a routine length is defined that will compute the length of a linked list by calling length on the cdr field as long as it is also a pair.

Running this program demonstrates that a call to length will be rejected. In the definition of the Main actor behaviour, an instance of Pair is created (and stored in variable p1), and via a call to its set-second! method it is made to point to itself. A subsequent call to its length method of the pair is successfully rejected by the interpreter. This call would otherwise result in an infinite loop.

Try it out! Remove the method invocation (length p1), either by removing the line of code entirely, or by adding // at the front (commenting out the line), and re-run the program. Now that the offending invocation is gone, the program no longer throws an error.