Skip to content

Instantly share code, notes, and snippets.

@TyOverby
Last active September 11, 2017 19:56
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 TyOverby/280a5cec2bebf703403d4c5f7b11527d to your computer and use it in GitHub Desktop.
Save TyOverby/280a5cec2bebf703403d4c5f7b11527d to your computer and use it in GitHub Desktop.
(define with-dynamic-var (sym val f)
    (define rec (f) 
        (match (reset (cons 'dyn sym) f)
            ({#finished, value} value)
            ({#shifted, {#lookup, cont}} (rec (thunk (continue cont val))))
            ({#shifted, {#mut, value, cont}} (with-dynamic-var sym value (thunk (continue cont))))
    (rec f))

(define lookup (sym)
    (shift (cons 'dyn sym) (lambda (c) {#lookup, cont: c})))

(define mutate (sym newval) 
    (shift (cons 'dyn sym) (lambda (c) {#mut, value: newval, cont: c})))

Example

(with-dynamic-var 'x 5 (lambda () 
  (f) ;; prints 5
  (mutate 'x 10)
  (f)) ;; prints 10

(define f () 
  (print (lookup 'x)))
@TyOverby
Copy link
Author

function with_dynamic_var(sym, val, f) {
    function rec(f) {
        return match reset(['dyn, sym], f) {
            {#finished, value} => value,
            {#shifted, cont} => rec(function () { return continue(cont, val) })
        }
    }

    return rec(f);
}

function lookup(sym) {
    return shift(['dyn sym], function(a) { return a });
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment