25 - Smalltalk#
Collections#

Differences among collections:

Collection Methods#
aCollection do: aBlock
aCollection add: newObject
aCollection remove: oldObject
Issues with Collections#
Two operations can’t be intermingled
Two collections can’t be iterated at the same time
Streams#


atEnd
- Has the final item been consumed?next
- Answer the next item in the streamdo:
- Iterate through a stream
Stream Hierarchy#
Stream
PositionableStream
ReadStream
WriteStream
ReadWriteStream
PositionableStream#
position
- Get the current position of the streamposition: n
- Set the current position of the streamreset
- Set the position to the front of the collectionsetToEnd
- Set the position to the end of the collectionskip: n
- Skip the next n elementspeek
- Answer the next element without movingcontents
- Answer the whole contents of the streamupToEnd
- Answer all items up to the stream’s end
ReadStream#
rs := ReadStream on: 'Mary had a little lamb'.
rs next.
rs upTo: $ .
rs nextLine.
WriteStream#
rs := WriteStream on: Array new.
nextPut: item "Put a single item"
nextPutAll: collection "Put a collection"
next: n put: item "Put n copies of item"
ReadWriteStream#
A ReadWriteStream
combines ReadStream
and WriteStream
.
ReadWriteStream
answers to the same messages as ReadStream
and WriteStream
.
Random access is allowed.
FileStream#
Opening:
f := FileStream open: 'data' mode: #read
f := FileStream open: 'data' mode: #write
ifFail: aBlock
Closing:
f close
Reading#
next
- Answer the next elementnext: n
- Answer the next n elements as a collectionnextLine
- Answer up to the next line delimiternextMatchFor: anObject
- Check if the next item isanObject
skip: n
- Skip n itemsskipTo: item
- Skip items to the next occurrence ofitem
skipToAll: aCollection
- Skip items toaCollection
upTo: item
- Return items up to next occurrences ofitem
upToAll: aCollection
- Return items up toaCollection
Reading all lines:
b := f nextLine.
[f atEnd] whileFalse:
[
b displayN1.
b := f nextLine.
].
Writing#
nextPut: item
- Put a single itemnextPutAll: collection
- Put a collectionnext: n put: item
- Put n copies of item
'Enter a binary expresssion: ' display.
expr := stdin nextLine.
tokens:=expr subStrings.
1 to: 3 do: [:index | (tokens at: index) printNl].
a:= (tokens at: 1) asNumber.
b:= (tokens at: 3) asNumber.
((tokens at: 2) = '+') ifTrue: [
c:=(a+b).
'The sum is ' display.
c displayNl.]