Skip to content

Instantly share code, notes, and snippets.

@darkf
Last active August 29, 2015 14:01
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 darkf/f7ae642e7272e3bf1fea to your computer and use it in GitHub Desktop.
Save darkf/f7ae642e7272e3bf1fea to your computer and use it in GitHub Desktop.
Closures as Stateful Objects
#lang racket
(define (obj state msg)
(match msg
['init (cons state (curry obj state))]
['get-x (cons state (curry obj state))]
[(list 'set-x x) (cons x (curry obj x))]
['ping (cons "pong" (curry obj state))]))
(define-syntax-rule (send! obj msg)
(let ([res (obj 'msg)])
(set! obj (cdr res))
(car res)))
(match-define (cons _ derp) (obj 5 'init))
(printf "~a\n" (send! derp get-x))
(printf "~a\n" (send! derp ping))
(printf "~a\n" (send! derp (set-x 10)))
(printf "~a\n" (send! derp get-x))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment