Skip to content

Instantly share code, notes, and snippets.

@rocketnia
Created March 29, 2022 22:41
Show Gist options
  • Save rocketnia/afd9e02d77f02de0ac827ab86cdb2f62 to your computer and use it in GitHub Desktop.
Save rocketnia/afd9e02d77f02de0ac827ab86cdb2f62 to your computer and use it in GitHub Desktop.
Implementing mutation using delimited control
#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