Skip to content

Instantly share code, notes, and snippets.

@erkin
Last active April 7, 2021 17:08
Show Gist options
  • Save erkin/e25bdf12e76f0c3d08dbac949d37476d to your computer and use it in GitHub Desktop.
Save erkin/e25bdf12e76f0c3d08dbac949d37476d to your computer and use it in GitHub Desktop.
Useful Scheme macros I keep rewriting for every project
(define-syntax define-syntax-rule
(syntax-rules ()
((_ (name args ...) body)
(define-syntax name
(syntax-rules ()
((name args ...) body))))))
(define-syntax-rule (do-times n . body)
(do ((i n (sub1 i)))
((< i 1))
. body))
(define-syntax-rule (until condition . body)
(do () (condition) . body))
(define-syntax-rule (forever . body)
(until #f . body))
(define-syntax-rule (if-let (value condition) yes no)
(let ((value condition))
(if value yes no)))
(define-syntax-rule (when-let (value condition) . body)
(let ((value condition))
(when value . body)))
(define-syntax-rule (if-not condition yes no)
(if condition no yes))
(define-syntax-rule (update! x f)
(set! x (f x)))
(define-syntax-rule (increment! x)
(update! x add1))
(define-syntax-rule (decrement! x)
(update! x sub1))
(define-syntax-rule (thunk body body* ...)
(lambda () body body* ...))
(define-syntax-rule (thunk* body body* ...)
(lambda ignored body body* ...))
(define-syntax ->
(syntax-rules ()
((_ x)
x)
((_ x (f arg ...) rest ...)
(-> (f x arg ...) rest ...))
((_ x f rest ...)
(-> (f x) rest ...))))
(define-syntax ->>
(syntax-rules ()
((_ x)
x)
((_ x (f arg ...) rest ...)
(->> (f arg ... x) rest ...))
((_ x f rest ...)
(->> (f x) rest ...))))
(define-syntax do-to
(syntax-rules ()
((_ x)
x)
((_ x (f arg ...) rest ...)
(begin
(f arg ... x)
(do-to x rest ...)))
((_ x f rest ...)
(do-to x (f) rest ...))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment