Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Lisp boolean m-of-n short circuiting
; Inspired by http://symbo1ics.com/blog/?p=1352
(defmacro are-count-true (num first-arg &rest args)
"Short circuit boolean expressions, finding if NUM are true."
(cond ((not (numberp num)) (error "Count must be number!"))
((minusp num) (error "What does negative number mean?"))
((zerop num) t)
((> num (1+ (length args))) nil)
((= num 1) `(or ,first-arg ,@args))
((= num (1+ (length args))) `(and ,first-arg ,@args))
(t
(let ((next-num (1- num)) (arg-val (gensym)))
`(let ((,arg-val ,first-arg))
(if ,arg-val
(are-count-true ,next-num ,@args)
(are-count-true ,num ,@args)))))))
;; Examples
;; CL-USER> (are-count-true 2 (progn (print "1") t) (progn (print "2") t) (progn (print "3") t))
;;
;; "1"
;; "2"
;; t
;; CL-USER> (are-count-true 2 (progn (print "1") t) (progn (print "2") nil) (progn (print "3") t))
;;
;; "1"
;; "2"
;; "3"
;; t
;; CL-USER> (are-count-true 2 (progn (print "1") t) (progn (print "2") nil) (progn (print "3") nil))
;;
;; "1"
;; "2"
;; "3"
;; nil
;; CL-USER> (are-count-true 4 (progn (print "1") t) (progn (print "2") nil) (progn (print "3") nil))
;;
;; nil
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.