DEV Community

Discussion on: Fizz Buzz in Every Language

Collapse
 
gypsydave5 profile image
David Wickes

Here's some fun from the world of Common Lisp

Inoffensive version

(defun divides (divisor dividend)
  (= (mod divisor dividend) 0))

(defun fizzbuzz (n)
  (let ((fizz (when (divides n 3) "Fizz"))
        (buzz (when (divides n 5) "Buzz")))
    (if (or fizz buzz)
        (concatenate 'string fizz buzz)
        (write-to-string n))))

Offensive FizzBuzz Builder Macro

For when you want to define your own custom fizzbuzzer. Nice and easy to extend.

(defun divides (divisor dividend)
  (= (mod divisor dividend) 0))

(defmacro define-fizzbuzzer (name &body pairs)
  `(defun ,name (n)
     (let ((result nil))
       (dolist (p ',pairs)
         (let ((test-passed? (if (typep (first p) 'integer)
                                 (divides n (first p))
                                 (funcall (eval (first p)) n))))
           (when test-passed? (push (second p) result))))
       (if (null result)
           (write-to-string n)
           (apply #'concatenate 'string (nreverse result))))))

(define-fizzbuzzer fizz-buzz
  (3 "Fizz")
  (5 "Buzz"))

(define-fizzbuzzer fizz-buzz-bazz
  (3 "Fizz")
  (5 "Buzz")
  (7 "Bazz"))

Most Offensive Macrogeddon Too Hot for TV Version

For when you want to define your own custom matcher logic for each word in your custom fizzbuzzer. Still lets you put a single number in for 'divides by' logic.

(defmacro define-fizzbuzzer (name &body pairs)
  (let ((ps (clean-args pairs)))
    `(defun ,name (n)
       (let ((result nil))
         (dolist (p ',ps)
           (let ((test-passed? (funcall (eval (first p)) n)))
             (when test-passed? (push (second p) result))))
         (if (null result)
             (write-to-string n)
             (apply #'concatenate 'string (nreverse result)))))))

(defun clean-args (pairs)
  (mapcar #'clean-pair pairs))

(defun clean-pair (pair)
  (cond ((typep (first pair) 'integer)
         (list '#'(lambda (n) (divides n (first pair))) (second pair)))
        ((eq (caar pair) 'function)
         pair)
        (t (error "first element of pair must be either an integer or a function"))))

(defun prime? (n)
  "evaluates to t when n is prime. Highly inefficient"
  (loop for x from 2 to (round n 2) never (divides n x)))

(defun has-a-nine-in-it? (n)
 "does the decimal representation of this number have a 9 in it?"
 (some #'(lambda (c) (char= c #\9)) (write-to-string n)))

(define-fizzbuzzer fizz-buzz
  (3 "Fizz")
  (5 "Buzz"))

(define-fizzbuzzer fazz-bazz
  (#'prime? "Fazz")
  (#'has-a-nine-in-it? "Bazz"))
Collapse
 
renegadecoder94 profile image
Jeremy Grifski

Bring on the parentheses!