Search code examples
smalltalkpharo

Creating a Print method for a Stack in SmallTalk


I have a class called 'AStack'

Object subclass: #AStack
    instanceVariableNames: 'elements'
...

It contains an OrderedCollection Object that holds it's 'element objects'

initialize 
super initialize.
elements := OrderedCollection new

It's member classes push and pop, respectively:

push: anObject 
self elements addFirst: anObject 

pop
^self elements removeFirst 

I am trying to write a print method that uses timesRepeat to print the contents of the stack as well as empty it simultaneously. It calls the child class print method for each 'element' (print ^self name) and outputs it on the screen using 'Transcript'.

print
self size timesRepeat: [ Transcript show: elements print. self pop ]

Workspace code:

| o1 o2 stk |

o1 := Object new.
o1 name: 'object1'.

o2 := Object new.
o2 name: 'object2'.

stk := AStack new.
stk push: o1.
stk push: o2.

stk print.

Upon running the above code I get an error within Pharo that says MessageNotUnderstood: AStack>>elements.

If you need more code on my part don't hesitate to ask.


Solution

  • As far as I can guess, error occurs in stk push: o1. as #push: uses self elements and probably you don't have #elements method in AStack.

    Also for emptying your stack it will be more logical not to use self size timesRepeat: but [ self notEmpty ] whileTrue: [ … ] or other variations like [ self isEmpty ] whileFalse: [ … ]. It makes code more understandable.

    And as we talk about understandability, usually people do not expect that #print method will destroy their collection :)