You are familar with counting/dividing game Fizz Buzz.
You have Leiningen installed
Create a new project
%> lein new fizzbuzz
%> cd fizzbuzzTo run tests add plugin lein-test-refresh by adding :plugins to project.clj:
(defproject fizzbuzz "0.1.0-SNAPSHOT"
:description "FIXME: write description"
:url "http://example.com/FIXME"
:license {:name "Eclipse Public License"
:url "http://www.eclipse.org/legal/epl-v10.html"}
:dependencies [[org.clojure/clojure "1.5.1"]]
:plugins [[com.jakemccrary/lein-test-refresh "0.1.2"]])Now we run our tests
%> lein test-refreshYou should see the dummy test fail.
Editor: You may like LightTable but you can use any editor for this exercise.
Clojure cheat sheet
Replace the first dummy test with the following in test/fizzbuzz/core_test.clj
(deftest one-should-be-one
(is (= "1" (fizz-buzz 1))))Make it pass by replacing the dummy code with the following in src/fizzbuz/core.clj
(defn fizz-buzz [x]
(str 1))We could refactor out the subtle duplication between the test and code. Naw, I'll just triangulate.
(deftest two-should-be-two
(is (= "2" (fizz-buzz 2))))And to make it pass one small change
(defn fizz-buzz [x]
(str x))(deftest three-should-fizz
(is (= "Fizz" (fizz-buzz 3))))Passing
(defn fizz-buzz [x]
(if (zero? (mod x 3))
"Fizz"
(str x)))We are skipping testing for 4 because it doesn't add anything.
(deftest five-should-buzz
(is (= "Buzz" (fizz-buzz 5))))And passing
(defn fizz-buzz [x]
(if (zero? (mod x 3))
"Fizz"
(if (zero? (mod x 5))
"Buzz"
(str x))))(deftest six-should-fizz
(is (= "Fizz" (fizz-buzz 6))))Which we expect to pass.
What? It passed?
(deftest fifteen-should-fizz-buzz
(is (= "FizzBuzz" (fizz-buzz 15))))Passing
(defn fizz-buzz [x]
(cond
(zero? (mod x 15)) "FizzBuzz"
(zero? (mod x 3)) "Fizz"
(zero? (mod x 5)) "Buzz"
:else (str x)))(deftest sequence-fizz-buzz
(is (= '("1" "2" "Fizz" "4" "Buzz") (fizz-buzz-seq 1 5))))Passing
(defn fizz-buzz-seq [from to]
(map fizz-buzz (range from (inc to))))Finished! It is time for a cookie!
You may want to move on to the banking exercise.