in-nest-sequence
is a sequence generator that takes a function and an initial value, and the return value of invoking the function on the current value is used as the subsequent value. For example, (in-nest-sequence add1 0)
returns the sequence (0 1 2 3 4 ...)
.
Recently, soegaard challenged me to write a define-sequence-syntax
version of in-nest-sequence
, that is, a macro-based version. I decided to give it a try:
#lang racket
(require (for-syntax unstable/syntax))
(provide (rename-out [*in-nest-sequence in-nest-sequence]))
(define in-nest-sequence
(case-lambda
[(func init)
(make-do-sequence
(thunk (values identity func init #f #f #f)))]
[(func . inits)
(make-do-sequence
(thunk (values (curry apply values)
(lambda (args)
(call-with-values (thunk (apply func args)) list))
inits #f #f #f)))]))
(define-sequence-syntax *in-nest-sequence
(lambda () #'in-nest-sequence)
(lambda (stx)
(syntax-case stx ()
[[(x ...) (_ func init ...)]
(unless (= (syntax-length #'(x ...)) (syntax-length #'(init ...)))
(raise-syntax-error 'in-nest-sequence
(format "~a values required" (syntax-length #'(x ...)))
stx #'(init ...)))
(with-syntax ([for-arity (syntax-length #'(init ...))]
[(value ...) (generate-temporaries #'(init ...))]
[(y ...) (generate-temporaries #'(init ...))])
#'[(x ...) (:do-in ([(f) func])
(unless (procedure-arity-includes? f for-arity)
(raise-arity-error f (procedure-arity f) init ...))
([value init] ...)
#t
([(x ...) (values value ...)]
[(y ...) (f value ...)])
#t
#t
(y ...))])])))
I'm a complete noob at using define-sequence-syntax
, so I appreciate any and all style, performance, and/or general feedback about my code. (See the original post for some usage examples.)
(for/list ([x (in-nest-sequence 42 0)]) x)
can be improved if a(procedure? func)
test is inserted beforemake-do-sequence
is called. Also: I am a bit torn about removing the one-value case. I am not 100% sure the optimizer can produce code that works equally well from the multiple values case. \$\endgroup\$