Progress indicator for `for` loops: `in-heartbeat`

Waiting for the result of a large computation can be annoying.
Is the loop stuck?

The silly sequence below makes it easy to do something every nth time in a loop.
Such as displaying a progress indicator.

#lang racket

(define (in-heartbeat n beat)
  (make-do-sequence
   (lambda ()
     (values (λ (pos) (when (= pos n) (beat)) #f) ; pos->element
             (λ (pos) (if (= pos n) 0 (+ pos 1))) ; next-pos
             0                                    ; initial-pos
             (λ (pos) #t)                         ; continue?
             #f
             #f))))

(for/sum ([i  100]
          [x (in-heartbeat 10 (λ () (display ".")))])
  i)

; .........4950
13 Likes

This is excellent. I've been doing something similar except not as neatly. Thanks for sharing.

Sidethought: This would be worth putting in a module if you wanted to.

2 Likes

The only thing I'd change is make heartbeat one word -- I'll be forever mis-naming it otherwise : -)

1 Like

Done!

Need 20 characters.