Skip to content

Instantly share code, notes, and snippets.

Created December 14, 2021 21:02
What would you like to do?
Using Lisp Macros to Fact-Check Code at Compile Time
;; This code was extracted from a larger project
;; and used in a Twitter thread on using macros
;; to fact-check programmers at compile-time.
(defun -flags-for (num)
(format nil "~{~A~}"
(remove-if #'null
(and (evenp num) #\e)
(and (oddp num) #\o)
(and (> num 100) #\>)
(and (> num 900) #\e) ; [e]ven bigger
; (also: wrong)
(and (< num 20) #\<)))))
(defmacro flag! (&body body)
(let ((seen (make-hash-table)))
`(format nil "~{~A~}"
(remove-if #'null
,@(let ((forms nil))
(loop for (flag test) in body
(if (nth-value 1 (gethash flag seen))
(error (format nil "already seen flag ~S" flag)))
(setf (gethash flag seen) t)
(setf forms (cons `(and ,test ,flag) forms)))
(defun flags-for (num)
(#\e (evenp num))
(#\o (oddp num))
(#\> (> num 100))
(#\< (< num 20))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment