|
|
@@ -1,8 +1,8 @@
|
|
|
# Глава 7. Итераторы
|
|
|
|
|
|
-An iterator is a resumable `proc`. Iterators are usually invoked in for loops.
|
|
|
+Итератор — это возобновляемый `proc`. Итераторы обычно используются в циклах `for`.
|
|
|
|
|
|
-We have already seen the built-in iterators items and `..<`. If they were not built-in we could easily define them ourselves:
|
|
|
+Ранее уже были показаны встроенные итераторы `items` и `..<`. Если бы они не были встроенными, их можно было бы легко определить их самостоятельно:
|
|
|
|
|
|
```nim
|
|
|
iterator `..<`(a, b: int): int = # 1
|
|
|
@@ -15,14 +15,14 @@ iterator `..<`(a, b: int): int = # 1
|
|
|
yield s[i]
|
|
|
```
|
|
|
|
|
|
-- 1 An iterator is declared much like a `proc`. The `..<` operator takes two integers and produces an integer.
|
|
|
-- 2 We do not return a value, we `yield` it. The for loop that calls the iterator `..<` calls `..<` again and again, each time the control flow resumes where the iterator left off until the iterator’s while loop finishes. (When `i >= b`.)
|
|
|
-- 3 `inc i` means to increment the integer `i` by 1. It can be also be written as `i = i + 1` or `i += 1`.
|
|
|
-- 4 The items iterator calls the `..<` iterator. Iterators are called in for loops.
|
|
|
+- 1 Итератор объявляется почти так же, как `proc`. Оператор `..<` принимает два целых числа и возвращает целое число.
|
|
|
+- 2 Итератор не возвращает результат, вместо этого предоставляется `yield`. Цикл `for`, вызывающий итератор `..<`, вызывает `..<` снова и снова, и каждый раз поток управления возобновляется с того места, на котором остановился итератор, до тех пор, пока не завершится цикл `while` итератора. (Когда `i >= b`.)
|
|
|
+- 3 `inc i` означает увеличение целого числа `i` на 1. Это также можно записать как `i = i + 1` или `i += 1`.
|
|
|
+4 Итератор `items` вызывает итератор `..<`, а итераторы вызываются в циклах `for`.
|
|
|
|
|
|
-## 7.1. Yield
|
|
|
+## 7.1. yield
|
|
|
|
|
|
-A `yield` statement can be easily understood as a variation of a return statement: A return statement returns the control flow to the caller, potentially producing a value that the caller can receive:
|
|
|
+Оператор `yield` можно легко представить как разновидность оператора `return`: оператор `return` возвращает управление вызывающей стороне, потенциально возвращая значение, которое может получить вызывающая сторона:
|
|
|
|
|
|
```nim
|
|
|
proc find(haystack: string; needle: char): int =
|
|
|
@@ -32,11 +32,11 @@ proc find(haystack: string; needle: char): int =
|
|
|
let index = find("abcabc", 'c') # 3
|
|
|
```
|
|
|
|
|
|
-- 1 Return the value of `i` to the caller and do not continue with the execution of `find`. This implies that the for loop is left too.
|
|
|
-- 2 Return the value -1 to indicate that needle did not occur in haystack.
|
|
|
-- 3 We assign the value that find returns to a variable called index.
|
|
|
+- 1 Вернуть значение `i` вызывающей стороне и не продолжать выполнение `find`. Это означает, что цикл `for` тоже завершается.
|
|
|
+- 2 Вернуть значение `-1`, чтобы указать, что иголка не найдена в стоге сена.
|
|
|
+- 3 Присвоить значение, возвращаемое функцией `find`, переменной `index`.
|
|
|
|
|
|
-`find` returns the index of the first occurrence of needle inside haystack. It is not possible to resume its execution in order to retrieve the possible other occurrences of needle. An iterator like `findAll` can do that, thanks to the `yield` keyword:
|
|
|
+`find` возвращает индекс первого вхождения `needle` в `haystack`. Невозможно возобновить выполнение функции, чтобы найти другие возможные вхождения `needle`. Это может сделать итератор, например `findAll`, благодаря ключевому слову `yield`:
|
|
|
|
|
|
```nim
|
|
|
iterator findAll(haystack: string; needle: char): int =
|
|
|
@@ -46,6 +46,6 @@ iterator findAll(haystack: string; needle: char): int =
|
|
|
for index in findAll("abcabc", 'c'): discard # 3
|
|
|
```
|
|
|
|
|
|
-- 1 Return the value of `i` to the caller and continue with the execution of `findAll` later.
|
|
|
-- 2 Notice the absence of a `yield -1` statement. If the iterator does not yield more values, the calling for loop will stop.
|
|
|
-- 3 We iterate over all values that are produced by `findAll` and bind the current value to index.
|
|
|
+- 1 Вернуть значение `i` вызывающей стороне и продолжить выполнение `findAll` позже.
|
|
|
+- 2 Обратите внимание на отсутствие оператора `yield -1`. Если итератор не выдаст больше значений, цикл for завершится.
|
|
|
+- 3 Мы перебираем все значения, возвращаемые `findAll`, и привязываем текущее значение к индексу.
|