[racket-dev] for/fold feature request

From: oev (oev-racket at sibmail.com)
Date: Wed May 29 07:30:59 EDT 2013

Hi, all!

Using `for/fold' with more than one accumulator is inconvenient, when
there is a need for auxiliary operations with accumulators before return.

For example:

(define (partition pred lst)
  (define-values (a1 a2)
    (for/fold ([acc1 null]
               [acc2 null])
      ([v (in-list lst)])
      (if (pred v)
          (values (cons v acc1) acc2)
          (values acc1 (cons v acc2)))))
  (values (reverse a1)
          (reverse a2)))

In example, it's impossible to reverse accumulators without using
intermediate definitions and applying `values' again.

IMHO, very often in `loop with accumulator' cases, there is a final
operation with accumulator before return.

Is it possible to add ability for defining such final operation as
optional or keyword argument?

For example:

(define (partition pred lst)
  (for/fold ([acc1 null reverse]
             [acc2 null reverse])
    ([v (in-list lst)])
    (if (pred v)
        (values (cons v acc1) acc2)
        (values acc1 (cons v acc2))))))

... or even better:

(define (partition pred lst)
  (for/fold ([acc1 null #:do-finally reverse]
             [acc2 null #:do-finally reverse])
    ([v (in-list lst)])
    (if (pred v)
        (values (cons v acc1) acc2)
        (values acc1 (cons v acc2))))))





Posted on the dev mailing list.