Skip to content

Instantly share code, notes, and snippets.

@ElectricCoffee
Created September 21, 2022 09:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ElectricCoffee/9c801a8e1465c2b844e7c2ddeb289f8e to your computer and use it in GitHub Desktop.
Save ElectricCoffee/9c801a8e1465c2b844e7c2ddeb289f8e to your computer and use it in GitHub Desktop.
A simple loop implementation which makes use of `continue` and `break`, which works as you'd expect. All using the power of continuations!
#lang racket
(define LOOP/CC (box '()))
(define BREAK/CC (box '()))
(define (continue)
(let ((loop/cc (unbox LOOP/CC)))
(loop/cc loop/cc)))
(define (break)
(let ((break/cc (unbox BREAK/CC)))
(break/cc)))
(define (reset . bs)
(for-each (λ (b) (set-box! b '())) bs))
(define (loop body)
(let/cc break/cc
(set-box! BREAK/CC break/cc)
(set-box! LOOP/CC (call/cc identity))
(body)
(continue))
(reset LOOP/CC BREAK/CC))
(define x 0)
(loop (λ ()
(set! x (+ 1 x))
(when (odd? x) (continue))
(display x)
(when (> x 10) (break))
(displayln ", Hello!")))
;; Should print
;; 2, Hello!
;; 4, Hello!
;; 6, Hello!
;; 8, Hello!
;; 10, Hello!
;; 12
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment