Skip to content

Instantly share code, notes, and snippets.

@sleibrock
Created January 6, 2022 16:25
Show Gist options
  • Save sleibrock/9ed23f8b0f54b061b3bc3a2b381e121a to your computer and use it in GitHub Desktop.
Save sleibrock/9ed23f8b0f54b061b3bc3a2b381e121a to your computer and use it in GitHub Desktop.
Simple macro to integrate help messages with function definitions
#lang racket/base
#|
Wanted to add docstrings a-la Python to Racket
So I made a macro to do that lol
|#
(require (for-syntax racket/syntax racket/base racket/string))
(define *helplist* (make-parameter (make-immutable-hash)))
(define-syntax (Action! stx)
(syntax-case stx ()
[(_ (signature ...) helpmsg code)
(with-syntax
([siglist (syntax->datum #'(signature ...))])
(begin
(unless (andmap identifier? (syntax->list #'siglist))
(raise-syntax-error #f "Invalid identifiers given" stx))
(unless (string? (syntax->datum #'helpmsg))
(raise-syntax-error #f "Given helpmsg not a string" stx))
#`(begin
(unless (hash-has-key? (*helplist*) (car (syntax->list #'siglist)))
(*helplist*
(hash-set (*helplist*)
(syntax->datum (car (syntax->list #'siglist)))
helpmsg)))
(define (signature ...) code))))]))
; Usage
(Action! (do-nothing)
"This function does ... nothing"
(void))
(Action! (identity X)
"This is the identity function"
X)
(Action! (help)
"This one prints help lol"
(hash-map (*helplist*)
(lambda (k v)
(displayln (format "~a - ~a" k v)))))
; ta-da
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment