Skip to content

Commit

Permalink
Add Rust example to prior art
Browse files Browse the repository at this point in the history
Using the no-op `Waker`, we can express generators and coroutines in
Rust.  Let's close our list of prior art examples with that.
  • Loading branch information
traviscross committed Mar 29, 2024
1 parent 7eacd06 commit a021905
Showing 1 changed file with 25 additions and 0 deletions.
25 changes: 25 additions & 0 deletions text/3513-gen-blocks.md
Original file line number Diff line number Diff line change
Expand Up @@ -582,6 +582,31 @@ Note that there is no library being used here and that `yield` is not a keyword

[koka]: https://koka-lang.github.io/

## Rust

In Rust, `async` blocks are built on top of the coroutine transformation. Using a no-op `Waker`, it's possible to expose this transformation. With that, we can build generators. Without the assistance of macros, the result looks like this:

```rust
let odd_dup = |xs| {
Gen::new(async move |mut y| {
for x in xs {
if x % 2 == 1 {
y.r#yield(x * 2).await;
}
}
})
};

let odd_dup = pin!(odd_dup(1u8..20));
let odd_dup = odd_dup.init();

for (i, x) in odd_dup.enumerate() {
assert_eq!((i as u8 * 2 + 1) * 2, x);
}
```

Crates such as [`genawaiter`][] use this technique.

# Unresolved questions
[unresolved-questions]: #unresolved-questions

Expand Down

0 comments on commit a021905

Please sign in to comment.