Skip to content

Instantly share code, notes, and snippets.

@martinklepsch
Created September 28, 2015 15:50
Show Gist options
  • Save martinklepsch/b2448c86a62bcfd9cf73 to your computer and use it in GitHub Desktop.
Save martinklepsch/b2448c86a62bcfd9cf73 to your computer and use it in GitHub Desktop.
#lang racket/base
(provide line-loop)
(require racket/class)
(require (prefix-in gen/ racket/generic))
;; Feels like a lightweight approach but getting
;; struct fields can be very verbose
(gen/define-generics progressable
(working progressable)
(done progressable))
(struct progress-loop (format-str update update-interval done)
#:methods gen:progressable
[(define (working p)
(for ([s (progress-loop-update p)])
(display (format (progress-loop-format-str p) s))
(sleep (progress-loop-update-interval p))))
(define (done p)
(displayln (format (progress-loop-format-str p)
(progress-loop-done p))))])
(begin
(working (progress-loop "\rComputing [~a]" '("|" "/" "-" "\\") 0.1 "x"))
(done (progress-loop "\rComputing [~a]" '("|" "/" "-" "\\") 0.1 "x")))
(define ui-loop%
(class object%
(init-field format-str done updates
[update-interval 0.2])
(super-new)
(define/public (working)
(for ([s updates])
(display (format format-str s))
(sleep update-interval)))
(define/public (finish)
(displayln (format format-str done)))))
(begin
(send (new ui-loop% [format-str "\rComputing [~a]"] [updates '("|" "/" "-" "\\")] [done "x"]) working)
(send (new ui-loop% [format-str "\rComputing [~a]"] [updates '("|" "/" "-" "\\")] [done "x"]) finish))
;; Previous approach but functions that return multiple values
;; can't be passed to other functions and then later be destructured
;; with let-values
(define (line-loop format-str loop-inputs done-input)
(values
(λ () (for ([s loop-inputs])
(display (format format-str s))
(sleep 0.2)))
(λ () (displayln (format format-str done-input)))))
(let-values ([(working done) (line-loop "\rComputing [~a]" '("|" "/" "-" "\\") "x")])
(working)
(done))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment