Created
September 21, 2022 09:18
-
-
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!
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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