Created
March 29, 2022 22:41
-
-
Save rocketnia/afd9e02d77f02de0ac827ab86cdb2f62 to your computer and use it in GitHub Desktop.
Implementing mutation using delimited control
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/base | |
(require (only-in racket/control reset shift)) | |
(require (only-in racket/match match match-let*)) | |
(define (my-set! pointer value) | |
(shift k | |
`(my-set! ,pointer ,value ,k))) | |
(define (my-get pointer) | |
(shift k | |
`(my-get ,pointer ,k))) | |
(define (run-with-mutation uninitialized-value body) | |
(let loop ([state (hash)] [command (reset `(done ,(body)))]) | |
(match command | |
[`(my-set! ,pointer ,value ,k) | |
(loop (hash-set state pointer value) (k (void)))] | |
[`(my-get ,pointer ,k) | |
(loop state | |
(k (hash-ref state pointer (lambda () uninitialized-value))))] | |
[`(done ,result) result]))) | |
(run-with-mutation 1 | |
(lambda () | |
(match-let* ([uninitialized-val (my-get 'test-variable)] | |
[_ (my-set! 'test-variable 2)] | |
[second-val (my-get 'test-variable)] | |
[_ (my-set! 'test-variable 3)] | |
[third-val (my-get 'test-variable)]) | |
(list uninitialized-val second-val third-val)))) | |
; Output: '(1 2 3) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment