class ListNode < Object # ListNode is a subclass of Object. slot data; slot nextnode; def initialize ( data, nextnode ) # The parameters of a method are bound to the arguments # corresponding by position in the arglist vector. These # names are placed in the method invocation's frame. self.data = data; # The name self is bound to the receiver object # in a method invocation's frame. self.nextnode = nextnode; true; end; end; class List # If no superclass is specified, it is assumed to be Object. slot head = nil; slot size = 0; def empty? () self.size == 0; # The value of the last expression evaluated in the body # of a method is the value returned by the method. end; def add ( data ) var newnode = ListNode.new(); # A var declaration inserts a new name # into the current frame. # Using such a declaration insures that # we won't trash a variable in a # nonlocal environment. # # Method new of Class allocates a new # object belonging to that class. # A new object's slot vector is # initialized to all undef values. newnode.initialize(data, nil); if self.head == nil then self.head = newnode; self.size = 1; else newnode.nextnode = self.head; self.head = newnode; self.size = self.size + 1; end; return data; # return the value that was added end; def remove_head () self.head = self.head.nextnode; end; def to_s () var val = "List "; p = self.head; while p do val = val + p.data.to_s(); # The + operator on Strings # does concatenation. p = p.nextnode; end; val; end; end; class Stack < List def push ( item, *rest) # This shows the use of variable argument list. # The last *'d argument is the array containing # the rest of the arguments. self.add ( item ); if rest.length > 0 # Arrays must have a length slot (containing # the length of the array. self.push(rest); end; end; def pop () if self.empty?() then nil; else self.remove_head(); end; end; def to_s () var val = "Stack "; p = self.head; while p do val = val + p.data.to_s(); p = p.nextnode; end; val; end; end; list = List.new(); # If a name is introduced without a var, # it is inserted into the global frame. stack = Stack.new(); arr = [ 1,2,3,4]; ind = 0; while ind < 4 do list.add (arr[i]); ind = ind + 1; end; stack.push(arr[0], arr[1], arr[2], arr[3]); stack.pop(); print (list, stack);