12.2: Streams vs. Collections

Pharo by Example 5.0 · LibreTexts

0%

Contents

    Text

    Size
    100%
    Theme
    Typeface
    Line length
    Spacing

    From LibreTexts, under CC BY-SA 3.0, as the source states it; its equations are written in TeX, which the PDF shows typeset. This page at LibreTexts.

    12.2: Streams vs. Collections

    The collection protocol supports the storage, removal and enumeration
    of the elements of a collection, but does not allow these operations to be intermingled. For example, if the elements of an OrderedCollection are processed by a do: method, it is not possible to add or remove elements from inside the do: block. Nor does the collection protocol offer ways to iterate over two collections at the same time, choosing which collection goes forward and which does not. Procedures like these require that a traversal index or position reference is maintained outside of the collection itself: this is exactly the role of ReadStream, WriteStream and ReadWriteStream.

    These three classes are defined to stream over some collection. For example, the following snippet creates a stream on an interval, then it reads two elements.

    |r|
    r := ReadStream on: (1 to: 1000). r next.
    >>> 1
    r next.
    >>> 2
    r atEnd.
    >>> false
    

    WriteStreams can write data to the collection:

    |w|
    w := WriteStream on: (String new: 5). w nextPut: $a.
    w nextPut: $b.
    w contents.
    >>> 'ab'
    

    It is also possible to create ReadWriteStreams that support both the reading and writing protocols.

    Streams are not only meant for collections, they can be used for files or sockets too. The following example creates a file named test.txt, writes two strings to it, separated by a carriage return, and closes the file.

    StandardFileStream
        fileNamed: 'test.txt'
        do: [:str | str
                    nextPutAll: '123';
                    cr;
                    nextPutAll: 'abcd' ].
    

    The following sections present the protocols in more depth.


    This page titled 12.2: Streams vs. Collections was last modified on Sat, 19 Dec 2020 08:13:39 GMT and is shared under a CC BY-SA 3.0 license and was authored, remixed, and/or curated by via source content that was edited to the style and standards of the LibreTexts platform.