# Generators

값의 시퀀스를 게으르게(lazily) 생성해야 하는 경우, 제너레이터(generator) 함수를 사용하는 것이 좋습니다. Dart는 두 종류의 제너레이터 함수를 내장하고 있습니다:

* 동기(generator): [Iterable](https://api.dart.dev/stable/2.19.6/dart-core/Iterable-class.html) 객체를 반환합니다.
* 비동기(generator): [Stream](https://api.dart.dev/stable/2.19.6/dart-async/Stream-class.html) 객체를 반환합니다.

동기(generator) 함수를 구현하려면, 함수 본문을 `sync*`로 표시하고 `yield` 문을 사용하여 값을 전달하면 됩니다.

```dart
Iterable<int> naturalsTo(int n) sync* {
  int k = 0;
  while (k < n) yield k++;
}
```

비동기(generator) 함수를 구현하려면, 함수 본문을 `async*`로 표시하고 `yield` 문을 사용하여 값을 전달하면 됩니다.

```dart
Stream<int> asynchronousNaturalsTo(int n) async* {
  int k = 0;
  while (k < n) yield k++;
}
```

제너레이터(generator)가 재귀적(recursive)인 경우, yield\*을 사용하여 성능을 향상시킬 수 있습니다:

```dart
Iterable<int> naturalsDownFrom(int n) sync* {
  if (n > 0) {
    yield n;
    yield* naturalsDownFrom(n - 1);
  }
}
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://judongseok.gitbook.io/dartlang/functions/generators.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
