Skip to content

Commit 966827d

Browse files
committed
(docs) add example of generator lambda* macro
1 parent 6b68081 commit 966827d

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed

docs/docs/scheme-intro/continuations.md

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -236,3 +236,58 @@ The procedure `make-coroutine-generator` allows defining generators:
236236
```
237237

238238
With continuations, you can do a lot of cool new flow control structures.
239+
240+
## Generator macro
241+
242+
With help from macros and
243+
[SRFI-139](https://srfi.schemers.org/srfi-139/srfi-139.html) described in section about [Anaphoric Hygienic Macros](/docs/scheme-intro/macros#anaphoric-hygienic-macros) you can create an abstraction over generators:
244+
245+
```scheme
246+
(define-syntax-parameter yield
247+
(syntax-rules ()
248+
((_)
249+
(syntax-error "Use outside lambda*"))))
250+
251+
(define-syntax lambda*
252+
(syntax-rules ()
253+
((_ args body ...)
254+
(lambda args
255+
(make-coroutine-generator
256+
(lambda (cc)
257+
(syntax-parameterize
258+
((yield (syntax-rules ()
259+
((_ x) (cc x))
260+
((_) (cc)))))
261+
body ...)))))))
262+
263+
(define gen (lambda* (start end)
264+
(do ((i start (+ i 1)))
265+
((> i end))
266+
(yield i))))
267+
268+
(define (generator->list gen)
269+
(let loop ((item (gen))
270+
(result '()))
271+
(if (eof-object? item)
272+
(reverse result)
273+
(loop (gen) (cons item result)))))
274+
275+
(let ((counter (gen 1 10)))
276+
(display (generator->list counter))
277+
(newline))
278+
;; ==> (1 2 3 4 5 6 7 8 9 10)
279+
```
280+
281+
`lambda*` works similar to
282+
[JavaScript generators](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Generator):
283+
284+
```javascript
285+
function* gen(start, end) {
286+
for (let i = start; i <= end; ++i) {
287+
yield i;
288+
}
289+
}
290+
291+
Array.from(gen(1, 10));
292+
// ==> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
293+
```

0 commit comments

Comments
 (0)