简体   繁体   中英

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.

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 :)

In smalltalk all instance variables are strictly private. What it means is: the object will not understand the message 'elements' unless you explicitly define the accessors.

In your case, if you don't want to expose 'elements' through accessors, you can replace all occurrences of self elements by elements

Also, I don't see size defined anywhere. So the definition should look like:

AStack>>size
    ^elements size
    OrderedCollection subclass: Stack [
   <shape: #inherit>
   pop [
      |lastElement|
      lastElement := self last.
      self removeLast.
      ^lastElement
   ]

   push: value[
      self addLast: value.
   ]

]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM