Commit 1cdb407587727dfb76b2a5c2254cce3b5879cdc7

[pt_BR] More work on the chapter Streams.

Commit diff

PortugueseBook/Streams/Streams.tex

 
7171
7272O protocolo de coleções suporta armazenamento, remoção e enumeração de elementos de uma coleção, mas não permite que essas operações sejam misturadas. Por exemplo, se os elementos de um \clsind{OrderedCollection} são processados por um método \mthind{OrderedCollection}{do:}, não é possível adicionar ou remover elementos dentro desse bloco \ct{do:}.
7373Tampouco o protocolo de coleções fornece uma forma de se iterar em duas coleções ao mesmo tempo, escolhendo qual coleção avança e qual não avança. Procedimentos como este exigem que o índice transversal ou posição de referência seja mantido fora da própria coleção: é exatamente este o papel de \clsind{ReadStream}, \clsind{WriteStream} e \clsind{ReadWriteStream}.
74\clsind{ReadWriteStream}.
7574
76These three classes are defined to \emph{stream over} some collection.
77For example, the following snippet creates a stream on an interval,
78then it reads two elements.
75Estas três classes são definidas para criar fluxos a partir de alguma coleção.
76Por exemplo, o trecho de código a seguir cria um fluxo a partir de um intervalo, e lê dois elementos.
7977\needlines{5}
8078\begin{code}{@TEST |r|}
8179r := ReadStream on: (1 to: 1000).
8282r atEnd.--> false
8383\end{code}
8484
85\ct{WriteStream}s can write data to the collection:
85\ct{WriteStream}s podem escrever dados em uma coleção:
8686\begin{code}{@TEST |w|}
8787w := WriteStream on: (String new: 5).
8888w nextPut: $a.
9090w contents. --> 'ab'
9191\end{code}
9292
93It is also possible to create \ct{ReadWriteStream}s that support both
94the reading and writing protocols.
93Também é possível criar \ct{ReadWriteStream}s que suportem tanto o protocolo de leitura quanto o protocolo de escrita.
9594
96The main problem with \ct{WriteStream} and \ct{ReadWriteStream} is
97that they only support arrays and strings in Squeak. This is currently
98being changed by the development of a new library named Nile,
99but for now if you try to stream over another kind of
100collection, you will get an error:
95O principal problema com \ct{WriteStream} e \ct{ReadWriteStream} é que eles apenas suportam arrays e strings. Isso está sendo mudado com o desenvolvimento de uma nova biblioteca chamada Nile, mas por enquanto se você tentar criar fluxos a partir de outro tipo de coleção, você recebá um erro:
10196
10297\needlines{3}
10398\begin{code}{}
10499w := WriteStream on: (OrderedCollection new: 20).
105w nextPut: 12. --> raises an error
100w nextPut: 12. --> resulta numa excecao
106101\end{code}
107102
108Streams are not only meant for collections, they can be used for files or sockets
109too. The following example creates a file named \ct{test.txt}, writes two strings to it, separated by a carriage return, and closes the file.
103Fluxos não são apenas direcionado a coleções, eles podem ser usados em arquivos ou sockets também. O exemplo a seguir cria um arquivo chamado \ct{test.txt}, escreve duas strings separadas por uma quebra de linha, e fecha o arquivo.
110104
111105\needlines{3}
112106\begin{code}{}
113113\end{code}
114114\cmindex{FileStream class}{fileNamed:do:}
115115
116The following sections present the protocols in more depth.
116As seções a seguir apresentam tais protocolos em mais detalhes.
117117
118118%=============================================================
119\section{Streaming over collections}
119\section{Criando fluxos a partir de coleções}
120120
121Streams are really useful when dealing with collections of
122elements. They can be used for reading and writing elements in
123collections. We will now explore the stream features for the
124collections.
121Fluxos são muito úteis quando trabalhamos com coleções de elementos, podendo ser usados tanto para ler quanto para escrever elementos em coleções. Nós iremos agora explorar os recursos dos fluxos para coleções.
125122
126123%-----------------------------------------------------------------
127\subsection{Reading collections}
124\subsection{Lendo coleções}
128125
129This section presents features used for reading collections. Using a
130stream to read a collection essentially provides you a pointer into the collection. That pointer will move forward on reading and you can place it wherever you want. The class \clsindmain{ReadStream} should be used to read elements from collections.
126Esta seção apresenta os recursos usados para a leitura de coleções. Ao usar um fluxo para ler uma coleção, você recebe um ponteiro para a coleção. Este ponteiro irá se mover para frente conforme a leitura é feita, e você pode posicionar este ponteiro onde desejar. A classe \clsindmain{ReadStream} deve ser usada par ler elementos de coleções.
131127
132Methods \mthind{ReadStream}{next} and \mthind{ReadStream}{next:} are used to
133retrieve one or more elements from the collection.
128Os métodos \mthind{ReadStream}{next} e \mthind{ReadStream}{next:} são usados para obter um ou mais elementos da coleção.
134129
135130\begin{code}{@TEST |stream|}
136131stream := ReadStream on: #(1 (a b c) false).
143143stream next: 2. --> 'ef'
144144\end{code}
145145
146The message \mthind{PositionableStream}{peek} is used when you want to know what is the next element in
147the stream without going forward.
146A mensagem \mthind{PositionableStream}{peek} é usada quando você quer saber qual é o próximo elemento no fluxo sem precisar avançar.
148147
149148\begin{code}{@TEST |stream negative number|}
150149stream := ReadStream on: '-143'.
151negative := (stream peek = $-). "look at the first element without reading it"
150negative := (stream peek = $-). "olha para o primeiro elemento sem avancar"
152151negative. --> true
153negative ifTrue: [stream next]. "ignores the minus character"
152negative ifTrue: [stream next]. "ignora o caractere '-'"
154153number := stream upToEnd.
155154number. --> '143'
156155\end{code}
157156\noindent
158This code sets the boolean variable \ct{negative} according to the sign of the
159number in the stream and \ct{number} to its absolute value. The method
160\mthind{ReadStream}{upToEnd} returns everything from the current position to the end
161of the stream and sets the stream to its end. This code can be
162simplified using \mthind{PositionableStream}{peekFor:}, which moves forward if the following element equals the parameter and doesn't move otherwise.
157Este código define a variável \ct{negative} de acordo com o sinal do número no fluxo e a variável \ct{number} com o valor absoluto. O método \mthind{ReadStream}{upToEnd} retorna tudo a partir da posição corrente do fluxo até seu final. Este código pode ser simplificado usando \mthind{PositionableStream}{peekFor:}, que avança caso o elemento a seguir seja igual ao parâmetro.
163158
164159\begin{code}{@TEST |stream negative number|}
165160stream := '-143' readStream.
162162stream upToEnd --> '143'
163163\end{code}
164164\noindent
165\ct{peekFor:} also returns a boolean
166indicating if the parameter equals the element.
165\ct{peekFor:} também retorna um valor booleano indicando se o parâmetro é igual ao elemento.
167166
168You might have noticed a new way of constructing a stream in
169the above example: one can simply send \mthind{SequenceableCollection}{readStream} to a sequenceable collection to get a reading stream on that particular
170collection.
167Você pode ter percebido uma nova forma de se construir um fluxo no código acima: podemos simplesmente enviar \mthind{SequenceableCollection}{readStream} a uma coleção sequenciável para obter um fluxo de leitura nesta coleção em particular.
171168
172\paragraph{Positioning.} There are methods to position the stream
173pointer. If you have the index, you can go directly to it using
174\mthind{PositionableStream}{position:}. You can request the current position using
175\mthind{PositionableStream}{position}. Please remember that a stream is not positioned on an
176element, but between two elements. The index corresponding to the
177beginning of the stream is 0.
169\paragraph{Posicionamento.} Existem métodos para posicionar o ponteiro do fluxo. Se você sabe o índice, você pode ir diretamente a ele usando \mthind{PositionableStream}{position:}. Você pode requisitar a posição atual usando \mthind{PositionableStream}{position}. Lembre-se que um fluxo não é posicionado em um elemento, mas entre dois elementos. O índice que corresponde ao início do fluxo é 0.
178170
179You can obtain the state of the stream depicted in
180\figref{ab_cde} with the following code:
171Você pode obter o estado do fluxo mostrado na \figref{ab_cde} com o código a seguir:
181172
182173\begin{code}{@TEST |stream|}
183174stream := 'abcde' readStream.
178178
179179\begin{figure}[h!t]
180180\centerline{\includegraphics[scale=0.5]{ab_cdeStef}}
181\caption{A stream at position 2}
181\caption{Um fluxo na posição 2.}
182182\label{fig:ab_cde}
183183\vspace{.2in}
184184\end{figure}
185185
186If you want to go to the beginning or at the end is what you want, you can use
187\mthind{PositionableStream}{reset} or \mthind{PositionableStream}{setToEnd}. \mthind{PositionableStream}{skip:} and \mthind{PositionableStream}{skipTo:} are used to
188go forward to a location relative to the current position: \ct{skip:}
189accepts a number as argument and skips that number of elements whereas
190\ct{skipTo:} skips all elements in the stream until it finds an
191element equals to its parameter. Note that it positions the stream
192after the matched element.
186Se você quer ir para o início ou final, você pode usar \mthind{PositionableStream}{reset} ou \mthind{PositionableStream}{setToEnd}. \mthind{PositionableStream}{skip:} e \mthind{PositionableStream}{skipTo:} são usados para avançar para uma posição relativa à posição atual: \ct{skip:} aceita como argumento um número que representa a quantidade de elementos a serem omitidos enquanto \ct{skipTo:} omite todos os elementos no fluxo até que ele encontre um elemento igual ao valor recebido no parâmetro. Note que ele posiciona o ponteiro após o elemento encontrado.
193187
194188\begin{code}{@TEST |stream|}
195189stream := 'abcdef' readStream.
196stream next. --> $a "stream is now positioned just after the a"
197stream skip: 3. "stream is now after the d"
190stream next. --> $a "ponteiro esta posicionado logo apos o 'a'"
191stream skip: 3. "ponteiro esta agora apos o 'd'"
198192stream position. --> 4
199stream skip: -2. "stream is after the b"
193stream skip: -2. "ponteiro esta agora apos o 'b'"
200194stream position. --> 2
201195stream reset.
202196stream position. --> 0
203stream skipTo: $e. "stream is just after the e now"
197stream skipTo: $e. "ponteiro agora esta apos o 'e'"
204198stream next. --> $f
205199stream contents. --> 'abcdef'
206200\end{code}
207201
208As you can see, the letter \ct{e} has been skipped.
202Como você pode ver, a letra \ct{e} foi omitida.
209203
210The method \mthind{PositionableStream}{contents} always returns a copy of the entire stream.
204O método \mthind{PositionableStream}{contents} sempre retorna uma cópia do fluxo.
211205
212\paragraph{Testing.} Some methods allow you to test the state of the current stream:
213\mthind{PositionableStream}{atEnd} returns true if and only if no more elements can be read whereas \mthind{PositionableStream}{isEmpty} returns true if and only if there is no element at all in the collection.
206\paragraph{Testando.} Alguns métodos permitem que você teste o estado atual do fluxo: \mthind{PositionableStream}{atEnd} retorna true se, e somente se, não existem outros elementos a serem lidos enquanto \mthind{PositionableStream}{isEmpty} retorna true se, e somente se, não existirem elementos na coleção.
214207
215Here is a possible implementation of an algorithm using \ct{atEnd} that takes two sorted collections as parameters and merges those collections into another sorted collection:
208Aqui está uma possível implementação de um algoritmo usando \ct{atEnd} que recebe duas coleções ordenadas como parâmetros e as combina em uma terceira coleção ordenada:
216209
217210\needlines{4}
218211\begin{code}{@TEST |stream1 stream2 result|}
219212stream1 := #(1 4 9 11 12 13) readStream.
220213stream2 := #(1 2 3 4 5 10 13 14 15) readStream.
221214
222"The variable result will contain the sorted collection."
215"A variavel result ira conter a colecao ordenada."
223216result := OrderedCollection new.
224217[stream1 atEnd not & stream2 atEnd not]
225218 whileTrue: [stream1 peek < stream2 peek
226 "Remove the smallest element from either stream and add it to the result."
219 "Remove o menor elemento de ambos os fluxos e o adiciona em result."
227220 ifTrue: [result add: stream1 next]
228221 ifFalse: [result add: stream2 next]].
229222
230"One of the two streams might not be at its end. Copy whatever remains."
223"Um dos dois fluxos podem nao ter chegado ao fim. Copia o que sobrar."
231224result
232225 addAll: stream1 upToEnd;
233226 addAll: stream2 upToEnd.
229229\end{code}
230230
231231%-----------------------------------------------------------------
232\subsection{Writing to collections}
232\subsection{Escrevendo em coleções}
233233
234We have already seen how to read a collection by iterating over its
235elements using a \ct{ReadStream}. We'll now learn how to create
236collections using \clsindmain{WriteStream}{}s.
234Nós acabamos de ver como iterar nos elementos de uma coleção usando \ct{ReadStream}. Agora nós iremos aprender como criar coleções usando \clsindmain{WriteStream}{}s.
237235
238236\ct{WriteStream}s are useful for appending a lot of data to a collection at various locations. They are often used to construct strings that are based on static and dynamic parts as in this example:
239237
toggle raw diff