Skip to content

Instantly share code, notes, and snippets.

@jadudm
Last active December 12, 2018 12:59
Show Gist options
  • Save jadudm/2a1960867223773f09aef41ec551bd3f to your computer and use it in GitHub Desktop.
Save jadudm/2a1960867223773f09aef41ec551bd3f to your computer and use it in GitHub Desktop.
Code for asking question on plt-users about macros as scopes.
#lang racket
(require racket/gui)
(require (for-syntax syntax/parse racket/syntax))
(provide (all-defined-out))
(struct agent (id singular plural fields)
#:transparent)
(begin-for-syntax
(define (expand-breed-pred stx singular plural)
(with-syntax ([breed-pred? (format-id stx "~a?" singular)]
[breed (format-id stx "~a" singular)])
(syntax/loc stx
(define (breed-pred? o)
(and (agent? o)
(equal? (agent-singular o) 'breed))))))
(define (expand-breed-vec stx plural)
(with-syntax ([breed-vec (format-id stx "~a-vec" plural)])
(syntax/loc stx
(define breed-vec (make-vector 0)))))
(define (expand-breed-fields stx singular)
(with-syntax ([breed-fields (format-id stx "~a-vec" singular)])
(syntax/loc stx
(define breed-fields empty))))
(define (expand-ask-breed stx plural)
(with-syntax ([ask-breed (format-id stx "ask-~a" plural)]
[breed-vec (format-id stx "~a-vec" plural)]
[(_ fields ...) stx])
(syntax/loc stx
(define-syntax (ask-breed stx-inner)
(syntax-parse stx-inner
[(_ bodies (... ...))
(syntax/loc stx-inner
(for ([critter breed-vec])
(parameterize ([current-agent critter])
bodies (... ...))
))]
)))))
)
(define-syntax (define-breed stx)
(syntax-parse stx
[(_ singular plural)
#`(begin
#,(expand-breed-vec stx #'plural )
#,(expand-breed-fields stx #'singular )
#,(expand-breed-pred stx #'singular #'plural )
#,(expand-ask-breed stx #'plural )
)]))
#lang racket
(require "world.rkt"
"scopes-base.rkt")
(define current-agent (make-parameter false))
(define-breed fish fishes)
(ask-fishes
(printf "Hello from a fish.~n"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment