[racket] Style. for/fold for/list for/lists
Replying to the entire list is hard to remember...
This doesn't have the full fanciness of the for--- series, but perhaps this
is a useful starting point along your suggested API?
(define (make-collector init-val mappend)
(let ([v init-val])
(λ args
(case (length args)
[(0) v]
[(1) (set! v (mappend (car args) v))]
[else (error "for/collect: blah blah blah")]))))
(define-syntax collector
(syntax-rules (list sum)
[(_ sum) (make-collector 0 +)]
[(_ list) (make-collector '() cons)]
;etc.
))
(define-syntax-rule (for/collect ([acc type] ...) ([i lst] ...) body ...)
(let ([acc (collector type)] ...)
(let loop ([i lst] ...)
(cond [(or (null? i) ...) (values (acc) ...)]
[else (let ([i (car i)] ...)
body ...)
(loop (cdr i) ...)]))))
It does use set!, as you feared, but since it's entirely local to the
collector implementation I don't think it counts as breaking purity.
On Wed, Jan 22, 2014 at 6:49 PM, Sean Kanaley <skanaley at gmail.com> wrote:
> This doesn't have the full fanciness of the for--- series, but perhaps
> this is a useful starting point along your suggested API?
>
> (define (make-collector init-val mappend)
> (let ([v init-val])
> (λ args
> (case (length args)
> [(0) v]
> [(1) (set! v (mappend (car args) v))]
> [else (error "for/collect: blah blah blah")]))))
>
> (define-syntax collector
> (syntax-rules (list sum)
> [(_ sum) (make-collector 0 +)]
> [(_ list) (make-collector '() cons)]
> ;etc.
> ))
>
> (define-syntax-rule (for/collect ([acc type] ...) ([i lst] ...) body ...)
> (let ([acc (collector type)] ...)
> (let loop ([i lst] ...)
> (cond [(or (null? i) ...) (values (acc) ...)]
> [else (let ([i (car i)] ...)
> body ...)
> (loop (cdr i) ...)]))))
>
> It does use set!, as you feared, but since it's entirely local to the
> collector implementation I don't think it counts as breaking purity.
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.racket-lang.org/users/archive/attachments/20140122/923f2891/attachment.html>