Created
November 14, 2014 05:44
-
-
Save juxtin/2bcbfdea6b2f78bc06a5 to your computer and use it in GitHub Desktop.
FizzBuzz without Conditionals
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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