Define a stack class.
| %Make the class a public class. public. class teststack. public. init/0. init/2. contains/1. list/1. push/1. pop/1. private. parts List, Contains. headstack/3. endclass teststack. |
After the class was declared the definitions of the methods follow.
| %Initialise the stack teststack::init :- List := [], Contains := 0, !. |
By using the cut operator the interpreter does not search for another init/0 method. The assignment operator is used because even if 'List' or 'Contains' have a value the 'old' values are overwritten by the new values.
| teststack::init(List2, Contains2) :- List := List2, Contains := Contains2, !. %Get the number of items on the stack |
To get the value of an instance attribute the matching of arguments can be used, the argument of the contains/1 predicate has the same name as a variable of the class so the variable is treated as an instance variable.
| %Get the list of items that is on the stack teststack::list( List ). %Push element on top of stack teststack::push(X1) :- List := [X1|List], %Use the assignment operator NewContains is Contains + 1, %Use 'is' operator to force arithmetic evaluation Contains := NewContains, !. |
With the assignment operator it is possible to use the same variable in the left and the right operands. To force arithmetic evaluation the operator is/2 is used.
| %Pop element from top of stack teststack::pop(X1) :- headstack(List, X1, Tail), %Compose list of stack in head and tail List := Tail, %Assign tail as the list of the stack NewContains is Contains - 1, Contains := NewContains, !. |
Retrieving the head of the list is done by matching with the private method 'headstack'/3.
| %Private predicate to compose the list into head and tail, fails if the
stack is empty teststack::headstack( [Head | Tail], Head, Tail ). teststack::headstack( [Head], Head, [] ). |
The method 'headstack/3' is is a nice example of the fact that a method can consist of multiple clauses.
A new instance can be created and initialised by the goal: X new_obj teststack, X<-init.
After the new instance was created it is asserted to the current module, because the class teststack has two attributes the following goal can be used to iterate through all the instances: teststack(V,V2).
A message can be send to each instance by using the class name and the message operator; teststack(V,V2)<-push(a).
To delete all instances the del_obj operator can be used; del_obj teststack(V,V2). All instances that match with teststack(V,V2) are deleted.