DEV Community

Discussion on: [Challenge] 🐝 FizzBuzz without if/else

Collapse
 
wdhowe profile image
wdhowe

One of the ways in Clojure:

(defn divisible?
  "Determine if a number is divisible by the divisor with no remainders."
  [div num]
  (zero? (mod num div)))

(defn fizz-buzz
  "Fizz if divisible by 3, Buzz if divisible by 5, FizzBuzz if div by both, n if neither."
  [n]
  (cond-> nil ; threaded value starts with nil (falsey)
    (divisible? 3 n) (str "Fizz") ; if true, adds Fizz to the threaded value (nil)
    (divisible? 5 n) (str "Buzz") ; if true, adds Buzz to the threaded value (nil or Fizz)
    :always-true     (or n))) ; return the threaded value if not nil (Fizz/Buzz) or n

(let [start 1
      stop 20]
  (println "FizzBuzz:" start "-" stop)
  (doseq [x (range start (+ 1 stop))] (println (fizz-buzz x))))

Original idea seen here: clojuredocs.org/clojure.core/cond-...