Skip to content

Instantly share code, notes, and snippets.

@luistung
Last active March 16, 2025 16:14
Show Gist options
  • Save luistung/4a9a029060b9fe45e462970aa8952311 to your computer and use it in GitHub Desktop.
Save luistung/4a9a029060b9fe45e462970aa8952311 to your computer and use it in GitHub Desktop.
decorator like python in racket
#lang racket
(define-syntax (define-decorator stx)
(syntax-case stx ()
[(_ (dector EXEC_RESULT) body ...)
#`(define (dector fun)
(make-keyword-procedure
(lambda (kws kw-args . args)
(let-syntax ([EXEC_RESULT
(lambda (stx)
#'(keyword-apply fun kws kw-args args))])
body ...))))]))
;;define a decorator called begin-end
(define-decorator (begin-end EXEC_RESULT) (displayln "begin") EXEC_RESULT (displayln "end"))
;;decorate a function, eg. pretty-print
(require racket/pretty)
(define begin-end-pretty-print (begin-end pretty-print))
;;call the decorated function begin-end-pretty-print
(begin-end-pretty-print (+ 1 1) #:newline? #t)
@luistung
Copy link
Author

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