Skip to content

Instantly share code, notes, and snippets.

@juxtin
Created November 14, 2014 05:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save juxtin/2bcbfdea6b2f78bc06a5 to your computer and use it in GitHub Desktop.
Save juxtin/2bcbfdea6b2f78bc06a5 to your computer and use it in GitHub Desktop.
FizzBuzz without Conditionals
(ns unconditional-fizz-buzz
"Note: this namespace occupies a bizarro world where there are no conditionals."
(:refer-clojure :exclude [case cond cond-> cond->> condp if if-let
if-not if-some when when-let when-not when-some]))
(defn not-divisible-by
"Given a number (divisor), returns a closure that: takes a numerator and returns
false (divisible) or the numerator. Please excuse the double negative; it's just
that false is easier to replace later on."
[n]
(fn [x]
(and (pos? (mod x n))
x)))
(defn false-pred-replacer
"Returns a closure that: uses the given (numerical) predicate to
test a value, substituting the given string for a false result. If it's
already a string, just return that."
[f s]
(fn [x]
(or (and (string? x)
x)
(and (number? x)
(f x))
s)))
(def fizzbuzz (false-pred-replacer (not-divisible-by 15) "fizzbuzz"))
(def fizz (false-pred-replacer (not-divisible-by 3) "fizz"))
(def buzz (false-pred-replacer (not-divisible-by 5) "buzz"))
(defn fizz-buzz []
(->> (range 1 101)
(map fizzbuzz)
(map fizz)
(map buzz)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment