Skip to content

Instantly share code, notes, and snippets.

@howeyc
Created May 4, 2012 14:52
Show Gist options
  • Save howeyc/2595259 to your computer and use it in GitHub Desktop.
Save howeyc/2595259 to your computer and use it in GitHub Desktop.
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