| |   |
| 71 | 71 | |
| 72 | 72 | O 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:}. |
| 73 | 73 | Tampouco 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}. |
| 75 | 74 | |
| 76 | | These three classes are defined to \emph{stream over} some collection. |
| 77 | | For example, the following snippet creates a stream on an interval, |
| 78 | | then it reads two elements. |
| 75 | Estas três classes são definidas para criar fluxos a partir de alguma coleção. |
| 76 | Por exemplo, o trecho de código a seguir cria um fluxo a partir de um intervalo, e lê dois elementos. |
| 79 | 77 | \needlines{5} |
| 80 | 78 | \begin{code}{@TEST |r|} |
| 81 | 79 | r := ReadStream on: (1 to: 1000). |
| … | … | |
| 82 | 82 | r atEnd.--> false |
| 83 | 83 | \end{code} |
| 84 | 84 | |
| 85 | | \ct{WriteStream}s can write data to the collection: |
| 85 | \ct{WriteStream}s podem escrever dados em uma coleção: |
| 86 | 86 | \begin{code}{@TEST |w|} |
| 87 | 87 | w := WriteStream on: (String new: 5). |
| 88 | 88 | w nextPut: $a. |
| … | … | |
| 90 | 90 | w contents. --> 'ab' |
| 91 | 91 | \end{code} |
| 92 | 92 | |
| 93 | | It is also possible to create \ct{ReadWriteStream}s that support both |
| 94 | | the reading and writing protocols. |
| 93 | Também é possível criar \ct{ReadWriteStream}s que suportem tanto o protocolo de leitura quanto o protocolo de escrita. |
| 95 | 94 | |
| 96 | | The main problem with \ct{WriteStream} and \ct{ReadWriteStream} is |
| 97 | | that they only support arrays and strings in Squeak. This is currently |
| 98 | | being changed by the development of a new library named Nile, |
| 99 | | but for now if you try to stream over another kind of |
| 100 | | collection, you will get an error: |
| 95 | O 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: |
| 101 | 96 | |
| 102 | 97 | \needlines{3} |
| 103 | 98 | \begin{code}{} |
| 104 | 99 | w := WriteStream on: (OrderedCollection new: 20). |
| 105 | | w nextPut: 12. --> raises an error |
| 100 | w nextPut: 12. --> resulta numa excecao |
| 106 | 101 | \end{code} |
| 107 | 102 | |
| 108 | | Streams are not only meant for collections, they can be used for files or sockets |
| 109 | | too. The following example creates a file named \ct{test.txt}, writes two strings to it, separated by a carriage return, and closes the file. |
| 103 | Fluxos 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. |
| 110 | 104 | |
| 111 | 105 | \needlines{3} |
| 112 | 106 | \begin{code}{} |
| … | … | |
| 113 | 113 | \end{code} |
| 114 | 114 | \cmindex{FileStream class}{fileNamed:do:} |
| 115 | 115 | |
| 116 | | The following sections present the protocols in more depth. |
| 116 | As seções a seguir apresentam tais protocolos em mais detalhes. |
| 117 | 117 | |
| 118 | 118 | %============================================================= |
| 119 | | \section{Streaming over collections} |
| 119 | \section{Criando fluxos a partir de coleções} |
| 120 | 120 | |
| 121 | | Streams are really useful when dealing with collections of |
| 122 | | elements. They can be used for reading and writing elements in |
| 123 | | collections. We will now explore the stream features for the |
| 124 | | collections. |
| 121 | Fluxos 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. |
| 125 | 122 | |
| 126 | 123 | %----------------------------------------------------------------- |
| 127 | | \subsection{Reading collections} |
| 124 | \subsection{Lendo coleções} |
| 128 | 125 | |
| 129 | | This section presents features used for reading collections. Using a |
| 130 | | stream 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. |
| 126 | Esta 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. |
| 131 | 127 | |
| 132 | | Methods \mthind{ReadStream}{next} and \mthind{ReadStream}{next:} are used to |
| 133 | | retrieve one or more elements from the collection. |
| 128 | Os métodos \mthind{ReadStream}{next} e \mthind{ReadStream}{next:} são usados para obter um ou mais elementos da coleção. |
| 134 | 129 | |
| 135 | 130 | \begin{code}{@TEST |stream|} |
| 136 | 131 | stream := ReadStream on: #(1 (a b c) false). |
| … | … | |
| 143 | 143 | stream next: 2. --> 'ef' |
| 144 | 144 | \end{code} |
| 145 | 145 | |
| 146 | | The message \mthind{PositionableStream}{peek} is used when you want to know what is the next element in |
| 147 | | the stream without going forward. |
| 146 | A mensagem \mthind{PositionableStream}{peek} é usada quando você quer saber qual é o próximo elemento no fluxo sem precisar avançar. |
| 148 | 147 | |
| 149 | 148 | \begin{code}{@TEST |stream negative number|} |
| 150 | 149 | stream := ReadStream on: '-143'. |
| 151 | | negative := (stream peek = $-). "look at the first element without reading it" |
| 150 | negative := (stream peek = $-). "olha para o primeiro elemento sem avancar" |
| 152 | 151 | negative. --> true |
| 153 | | negative ifTrue: [stream next]. "ignores the minus character" |
| 152 | negative ifTrue: [stream next]. "ignora o caractere '-'" |
| 154 | 153 | number := stream upToEnd. |
| 155 | 154 | number. --> '143' |
| 156 | 155 | \end{code} |
| 157 | 156 | \noindent |
| 158 | | This code sets the boolean variable \ct{negative} according to the sign of the |
| 159 | | number 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 |
| 161 | | of the stream and sets the stream to its end. This code can be |
| 162 | | simplified using \mthind{PositionableStream}{peekFor:}, which moves forward if the following element equals the parameter and doesn't move otherwise. |
| 157 | Este 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. |
| 163 | 158 | |
| 164 | 159 | \begin{code}{@TEST |stream negative number|} |
| 165 | 160 | stream := '-143' readStream. |
| … | … | |
| 162 | 162 | stream upToEnd --> '143' |
| 163 | 163 | \end{code} |
| 164 | 164 | \noindent |
| 165 | | \ct{peekFor:} also returns a boolean |
| 166 | | indicating if the parameter equals the element. |
| 165 | \ct{peekFor:} também retorna um valor booleano indicando se o parâmetro é igual ao elemento. |
| 167 | 166 | |
| 168 | | You might have noticed a new way of constructing a stream in |
| 169 | | the above example: one can simply send \mthind{SequenceableCollection}{readStream} to a sequenceable collection to get a reading stream on that particular |
| 170 | | collection. |
| 167 | Você 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. |
| 171 | 168 | |
| 172 | | \paragraph{Positioning.} There are methods to position the stream |
| 173 | | pointer. 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 |
| 176 | | element, but between two elements. The index corresponding to the |
| 177 | | beginning 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. |
| 178 | 170 | |
| 179 | | You can obtain the state of the stream depicted in |
| 180 | | \figref{ab_cde} with the following code: |
| 171 | Você pode obter o estado do fluxo mostrado na \figref{ab_cde} com o código a seguir: |
| 181 | 172 | |
| 182 | 173 | \begin{code}{@TEST |stream|} |
| 183 | 174 | stream := 'abcde' readStream. |
| … | … | |
| 178 | 178 | |
| 179 | 179 | \begin{figure}[h!t] |
| 180 | 180 | \centerline{\includegraphics[scale=0.5]{ab_cdeStef}} |
| 181 | | \caption{A stream at position 2} |
| 181 | \caption{Um fluxo na posição 2.} |
| 182 | 182 | \label{fig:ab_cde} |
| 183 | 183 | \vspace{.2in} |
| 184 | 184 | \end{figure} |
| 185 | 185 | |
| 186 | | If 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 |
| 188 | | go forward to a location relative to the current position: \ct{skip:} |
| 189 | | accepts a number as argument and skips that number of elements whereas |
| 190 | | \ct{skipTo:} skips all elements in the stream until it finds an |
| 191 | | element equals to its parameter. Note that it positions the stream |
| 192 | | after the matched element. |
| 186 | Se 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. |
| 193 | 187 | |
| 194 | 188 | \begin{code}{@TEST |stream|} |
| 195 | 189 | stream := 'abcdef' readStream. |
| 196 | | stream next. --> $a "stream is now positioned just after the a" |
| 197 | | stream skip: 3. "stream is now after the d" |
| 190 | stream next. --> $a "ponteiro esta posicionado logo apos o 'a'" |
| 191 | stream skip: 3. "ponteiro esta agora apos o 'd'" |
| 198 | 192 | stream position. --> 4 |
| 199 | | stream skip: -2. "stream is after the b" |
| 193 | stream skip: -2. "ponteiro esta agora apos o 'b'" |
| 200 | 194 | stream position. --> 2 |
| 201 | 195 | stream reset. |
| 202 | 196 | stream position. --> 0 |
| 203 | | stream skipTo: $e. "stream is just after the e now" |
| 197 | stream skipTo: $e. "ponteiro agora esta apos o 'e'" |
| 204 | 198 | stream next. --> $f |
| 205 | 199 | stream contents. --> 'abcdef' |
| 206 | 200 | \end{code} |
| 207 | 201 | |
| 208 | | As you can see, the letter \ct{e} has been skipped. |
| 202 | Como você pode ver, a letra \ct{e} foi omitida. |
| 209 | 203 | |
| 210 | | The method \mthind{PositionableStream}{contents} always returns a copy of the entire stream. |
| 204 | O método \mthind{PositionableStream}{contents} sempre retorna uma cópia do fluxo. |
| 211 | 205 | |
| 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. |
| 214 | 207 | |
| 215 | | Here 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: |
| 208 | Aqui 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: |
| 216 | 209 | |
| 217 | 210 | \needlines{4} |
| 218 | 211 | \begin{code}{@TEST |stream1 stream2 result|} |
| 219 | 212 | stream1 := #(1 4 9 11 12 13) readStream. |
| 220 | 213 | stream2 := #(1 2 3 4 5 10 13 14 15) readStream. |
| 221 | 214 | |
| 222 | | "The variable result will contain the sorted collection." |
| 215 | "A variavel result ira conter a colecao ordenada." |
| 223 | 216 | result := OrderedCollection new. |
| 224 | 217 | [stream1 atEnd not & stream2 atEnd not] |
| 225 | 218 | 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." |
| 227 | 220 | ifTrue: [result add: stream1 next] |
| 228 | 221 | ifFalse: [result add: stream2 next]]. |
| 229 | 222 | |
| 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." |
| 231 | 224 | result |
| 232 | 225 | addAll: stream1 upToEnd; |
| 233 | 226 | addAll: stream2 upToEnd. |
| … | … | |
| 229 | 229 | \end{code} |
| 230 | 230 | |
| 231 | 231 | %----------------------------------------------------------------- |
| 232 | | \subsection{Writing to collections} |
| 232 | \subsection{Escrevendo em coleções} |
| 233 | 233 | |
| 234 | | We have already seen how to read a collection by iterating over its |
| 235 | | elements using a \ct{ReadStream}. We'll now learn how to create |
| 236 | | collections using \clsindmain{WriteStream}{}s. |
| 234 | Nó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. |
| 237 | 235 | |
| 238 | 236 | \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: |
| 239 | 237 | |
| toggle raw diff |
--- a/PortugueseBook/Streams/Streams.tex
+++ b/PortugueseBook/Streams/Streams.tex
@@ -71,11 +71,9 @@ A escrita de um elemento significa substituir o primeiro elemento da sequência
O 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:}.
Tampouco 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}.
-\clsind{ReadWriteStream}.
-These three classes are defined to \emph{stream over} some collection.
-For example, the following snippet creates a stream on an interval,
-then it reads two elements.
+Estas três classes são definidas para criar fluxos a partir de alguma coleção.
+Por exemplo, o trecho de código a seguir cria um fluxo a partir de um intervalo, e lê dois elementos.
\needlines{5}
\begin{code}{@TEST |r|}
r := ReadStream on: (1 to: 1000).
@@ -84,7 +82,7 @@ r next. --> 2
r atEnd.--> false
\end{code}
-\ct{WriteStream}s can write data to the collection:
+\ct{WriteStream}s podem escrever dados em uma coleção:
\begin{code}{@TEST |w|}
w := WriteStream on: (String new: 5).
w nextPut: $a.
@@ -92,23 +90,17 @@ w nextPut: $b.
w contents. --> 'ab'
\end{code}
-It is also possible to create \ct{ReadWriteStream}s that support both
-the reading and writing protocols.
+Também é possível criar \ct{ReadWriteStream}s que suportem tanto o protocolo de leitura quanto o protocolo de escrita.
-The main problem with \ct{WriteStream} and \ct{ReadWriteStream} is
-that they only support arrays and strings in Squeak. This is currently
-being changed by the development of a new library named Nile,
-but for now if you try to stream over another kind of
-collection, you will get an error:
+O 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:
\needlines{3}
\begin{code}{}
w := WriteStream on: (OrderedCollection new: 20).
-w nextPut: 12. --> raises an error
+w nextPut: 12. --> resulta numa excecao
\end{code}
-Streams are not only meant for collections, they can be used for files or sockets
-too. The following example creates a file named \ct{test.txt}, writes two strings to it, separated by a carriage return, and closes the file.
+Fluxos 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.
\needlines{3}
\begin{code}{}
@@ -121,24 +113,19 @@ StandardFileStream
\end{code}
\cmindex{FileStream class}{fileNamed:do:}
-The following sections present the protocols in more depth.
+As seções a seguir apresentam tais protocolos em mais detalhes.
%=============================================================
-\section{Streaming over collections}
+\section{Criando fluxos a partir de coleções}
-Streams are really useful when dealing with collections of
-elements. They can be used for reading and writing elements in
-collections. We will now explore the stream features for the
-collections.
+Fluxos 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.
%-----------------------------------------------------------------
-\subsection{Reading collections}
+\subsection{Lendo coleções}
-This section presents features used for reading collections. Using a
-stream 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.
+Esta 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.
-Methods \mthind{ReadStream}{next} and \mthind{ReadStream}{next:} are used to
-retrieve one or more elements from the collection.
+Os métodos \mthind{ReadStream}{next} e \mthind{ReadStream}{next:} são usados para obter um ou mais elementos da coleção.
\begin{code}{@TEST |stream|}
stream := ReadStream on: #(1 (a b c) false).
@@ -156,23 +143,18 @@ stream next: 3. --> 'bcd'
stream next: 2. --> 'ef'
\end{code}
-The message \mthind{PositionableStream}{peek} is used when you want to know what is the next element in
-the stream without going forward.
+A mensagem \mthind{PositionableStream}{peek} é usada quando você quer saber qual é o próximo elemento no fluxo sem precisar avançar.
\begin{code}{@TEST |stream negative number|}
stream := ReadStream on: '-143'.
-negative := (stream peek = $-). "look at the first element without reading it"
+negative := (stream peek = $-). "olha para o primeiro elemento sem avancar"
negative. --> true
-negative ifTrue: [stream next]. "ignores the minus character"
+negative ifTrue: [stream next]. "ignora o caractere '-'"
number := stream upToEnd.
number. --> '143'
\end{code}
\noindent
-This code sets the boolean variable \ct{negative} according to the sign of the
-number in the stream and \ct{number} to its absolute value. The method
-\mthind{ReadStream}{upToEnd} returns everything from the current position to the end
-of the stream and sets the stream to its end. This code can be
-simplified using \mthind{PositionableStream}{peekFor:}, which moves forward if the following element equals the parameter and doesn't move otherwise.
+Este 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.
\begin{code}{@TEST |stream negative number|}
stream := '-143' readStream.
@@ -180,22 +162,13 @@ stream := '-143' readStream.
stream upToEnd --> '143'
\end{code}
\noindent
-\ct{peekFor:} also returns a boolean
-indicating if the parameter equals the element.
+\ct{peekFor:} também retorna um valor booleano indicando se o parâmetro é igual ao elemento.
-You might have noticed a new way of constructing a stream in
-the above example: one can simply send \mthind{SequenceableCollection}{readStream} to a sequenceable collection to get a reading stream on that particular
-collection.
+Você 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.
-\paragraph{Positioning.} There are methods to position the stream
-pointer. If you have the index, you can go directly to it using
-\mthind{PositionableStream}{position:}. You can request the current position using
-\mthind{PositionableStream}{position}. Please remember that a stream is not positioned on an
-element, but between two elements. The index corresponding to the
-beginning of the stream is 0.
+\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.
-You can obtain the state of the stream depicted in
-\figref{ab_cde} with the following code:
+Você pode obter o estado do fluxo mostrado na \figref{ab_cde} com o código a seguir:
\begin{code}{@TEST |stream|}
stream := 'abcde' readStream.
@@ -205,56 +178,49 @@ stream peek --> $c
\begin{figure}[h!t]
\centerline{\includegraphics[scale=0.5]{ab_cdeStef}}
-\caption{A stream at position 2}
+\caption{Um fluxo na posição 2.}
\label{fig:ab_cde}
\vspace{.2in}
\end{figure}
-If you want to go to the beginning or at the end is what you want, you can use
-\mthind{PositionableStream}{reset} or \mthind{PositionableStream}{setToEnd}. \mthind{PositionableStream}{skip:} and \mthind{PositionableStream}{skipTo:} are used to
-go forward to a location relative to the current position: \ct{skip:}
-accepts a number as argument and skips that number of elements whereas
-\ct{skipTo:} skips all elements in the stream until it finds an
-element equals to its parameter. Note that it positions the stream
-after the matched element.
+Se 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.
\begin{code}{@TEST |stream|}
stream := 'abcdef' readStream.
-stream next. --> $a "stream is now positioned just after the a"
-stream skip: 3. "stream is now after the d"
+stream next. --> $a "ponteiro esta posicionado logo apos o 'a'"
+stream skip: 3. "ponteiro esta agora apos o 'd'"
stream position. --> 4
-stream skip: -2. "stream is after the b"
+stream skip: -2. "ponteiro esta agora apos o 'b'"
stream position. --> 2
stream reset.
stream position. --> 0
-stream skipTo: $e. "stream is just after the e now"
+stream skipTo: $e. "ponteiro agora esta apos o 'e'"
stream next. --> $f
stream contents. --> 'abcdef'
\end{code}
-As you can see, the letter \ct{e} has been skipped.
+Como você pode ver, a letra \ct{e} foi omitida.
-The method \mthind{PositionableStream}{contents} always returns a copy of the entire stream.
+O método \mthind{PositionableStream}{contents} sempre retorna uma cópia do fluxo.
-\paragraph{Testing.} Some methods allow you to test the state of the current stream:
-\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.
+\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.
-Here 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:
+Aqui 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:
\needlines{4}
\begin{code}{@TEST |stream1 stream2 result|}
stream1 := #(1 4 9 11 12 13) readStream.
stream2 := #(1 2 3 4 5 10 13 14 15) readStream.
-"The variable result will contain the sorted collection."
+"A variavel result ira conter a colecao ordenada."
result := OrderedCollection new.
[stream1 atEnd not & stream2 atEnd not]
whileTrue: [stream1 peek < stream2 peek
- "Remove the smallest element from either stream and add it to the result."
+ "Remove o menor elemento de ambos os fluxos e o adiciona em result."
ifTrue: [result add: stream1 next]
ifFalse: [result add: stream2 next]].
-"One of the two streams might not be at its end. Copy whatever remains."
+"Um dos dois fluxos podem nao ter chegado ao fim. Copia o que sobrar."
result
addAll: stream1 upToEnd;
addAll: stream2 upToEnd.
@@ -263,11 +229,9 @@ result. --> an OrderedCollection(1 1 2 3 4 4 5 9 10 11 12 13 13 14 15)
\end{code}
%-----------------------------------------------------------------
-\subsection{Writing to collections}
+\subsection{Escrevendo em coleções}
-We have already seen how to read a collection by iterating over its
-elements using a \ct{ReadStream}. We'll now learn how to create
-collections using \clsindmain{WriteStream}{}s.
+Nó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.
\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:
|