Following up on FizzBuzz in Common Lisp, here’s FizzBuzz (the extended version) in Clojure. See my previous entry for more on FizzBuzz and what’s going on here.
I’m definitely nowhere near as familiar with Clojure as I am with Common Lisp, so things might not be done here in an idiomatic way.
The use of keyword arguments in a Clojure argument list was shamelessly cribbed from “Creative Clojure: Keyword arguments in Clojure“.
(defn fizzbuzz [& {:keys [from to tests] :or {from 1 to 100 tests '[[3 "Fizz"] [5 "Buzz"]]}}] (doseq [i (take (- to from -1) (iterate inc from))] (if (every? nil? (for [[divisor message] tests] (if (= (mod i divisor) 0) (do (print message) true)))) (print i)) (print " ")) (println))
And here’s how to use it, and the output:
(fizzbuzz :to 105 :tests '[[3 "Fizz"] [5 "Buzz"] [7 "Duck"]])
1 2 Fizz 4 Buzz Fizz Duck 8 Fizz Buzz 11 Fizz 13 Duck FizzBuzz 16 17 Fizz 19 Buzz FizzDuck 22 23 Fizz Buzz 26 Fizz Duck 29 FizzBuzz 31 32 Fizz 34 BuzzDuck Fizz 37 38 Fizz Buzz 41 FizzDuck 43 44 FizzBuzz 46 47 Fizz Duck Buzz Fizz 52 53 Fizz Buzz Duck Fizz 58 59 FizzBuzz 61 62 FizzDuck 64 Buzz Fizz 67 68 Fizz BuzzDuck 71 Fizz 73 74 FizzBuzz 76 Duck Fizz 79 Buzz Fizz 82 83 FizzDuck Buzz 86 Fizz 88 89 FizzBuzz Duck 92 Fizz 94 Buzz Fizz 97 Duck Fizz Buzz 101 Fizz 103 104 FizzBuzzDuck
nil
Now, I did use Google a fair bit in figuring out how to do this, since I am but a beginner in Clojure even though I have written more than a few lines of code in other languages. Any programmer who tells you they don’t use Google/StackOverflow daily in their work is lying. That’s (partly) why I don’t believe in pen-and-paper programming in interviews. Would you ask a surgeon to operate on an orange using a knife and a fork? If you don’t know what to look for, the best search engine in the world is not going to help.
I think I may have to dive a bit deeper into Clojure to see what the hoopla is all about. I guess being able to hook up to the Java virtual machine is a godsend for some.