13.07.2015 Views

Smalltalk Best Practice Patterns Volume 1: Coding - Free

Smalltalk Best Practice Patterns Volume 1: Coding - Free

Smalltalk Best Practice Patterns Volume 1: Coding - Free

SHOW MORE
SHOW LESS
  • No tags were found...

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

QueueHow do you implement a queue?The story for queues is much like the story for stacks. Everyone simulates them usingOrderedCollections:Queue OperationaddremoveemptylengthOrderedCollection messageaddFirst:removeLast:isEmptysizeAs with stacks, you lose a little by translating the queue operations into messages toOrderedCollection protocol, but not nearly enough to make up for the cost of adding a new class.Implement queues using an OrderedCollection.I have used OrderedCollections as queues a couple of ways. The most common is in implementinglevel-order traversal, where you need to visit all the depth 1 nodes of a tree before you visit thedepth 2 nodes and so on.Insert a diagram of a level order traversal.The code looks like this:Node>>levelOrderDo: aBlock| queue |queue := OrderedCollection with: self.[queue isEmpty] whileFalse:[| current |current := queue removeLast.aBlock value: current.queue addAllFirst: current children]You can implement a priority queue with a SortedCollection using add: and remove: instead ofaddFirst: and removeLast:.Sidebar:I can vividly remember the moment I became a computer scientist. I was in a first data structureclass taught by Andrzej Proskurowski at the University of Oregon. Gray light through the windowswashed most of the color out of the room (we are talking about Eugene, Oregon, here). I was justgetting comfortable with data structures as a concept separate from programming, but I was stillsquirming a bit sitting there, since Andrzej was a pretty aggressive professor.Andrzej had the size and energy of a hummingbird, but muscled like a gymnast. He had a thickblack goatee and an even thicker Polish accent. He kept us all on our toes with the simple trick ofcalling everyone by name after hearing the names exactly once. He had just presented a linked list<strong>Coding</strong> <strong>Patterns</strong> page 115 of 147 9/30/2006

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!