Skip to content

Instantly share code, notes, and snippets.

@samdphillips
Created March 31, 2021 18:57
Show Gist options
  • Save samdphillips/50f093029afe90f1231b201ab430bc76 to your computer and use it in GitHub Desktop.
Save samdphillips/50f093029afe90f1231b201ab430bc76 to your computer and use it in GitHub Desktop.
Simple macro making a closure over shared state.
#lang racket/base
(require (for-syntax syntax/parse/lib/function-header)
syntax/parse/define
racket/match
racket/undefined)
#|
(define fun (let (state ....) (lambda (args) (set! state ...))))
|#
(define-syntax-parse-rule
(define/local-state (name:id args:formals ...) (locals:id ...) body ...)
(define name
(let ([locals undefined] ...)
(lambda (args ...) body ...))))
(define/local-state (doit msg) (a b c)
(match msg
['assign
(set!-values (a b c) (values 1 2 3))]
['report
(list a b c)]))
(doit 'report)
;; => '(#<undefined> #<undefined> #<undefined>)
(doit 'assign)
(doit 'report)
;; => '(1 2 3)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment