Last active
August 29, 2015 14:01
-
-
Save darkf/f7ae642e7272e3bf1fea to your computer and use it in GitHub Desktop.
Closures as Stateful Objects
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 | |
(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