I just wanted to demonstrate a little of what I’ve learned. I’m sure you have done the problem fizzbuzz before.
In case you haven’t it is just counting however if the number is divisible by 3 you say “fizz” if the number is divisible by 5 you say “buzz” and if it is divisible by 3 and 5 you say “fizzbuzz “. Apparently, this is a kids game which I’m not sure would be very fun for children in general. I digress
This is a popular coding problem which should result in something like this. 1 2 "fizz" 4 "buzz" "fizz" 7 8 "fizz" "buzz" 11 "fizz" 13 14 "fizzbuzz"
. It sounds like being trapped in a tent with a few mosquitoes.
The fist time I completed this I came up with something like this:
(defn divisible-by [n div] (= 0 (mod n div)))
(defn fizzbuzz [n]
(let [nums (range 1 (inc n))]
(map #(cond
(and (divisible-by % 5) (divisible-by % 3)) "fizzbuzz"
(divisible-by % 5) "buzz"
(divisible-by % 3) "fizz"
:else %)
nums)))
As you can see it was a bit too messy. I did not like the 3 and 5 repeating especially if those numbers may change in the future. So I took out divisible-by %
part in fizzbuzz and made separate functions to only use 3 and 5 each once. For fizzbuzz?, I just used fizz? And buzz?
I still wasn’t fully convinced it looked good enough. There was too much going on in fizzbuzz.
So the thought was to take out the conditional and make a separate function. Then since there is only one function being used inside we can use the magical powers of threading.
Take a look:
``
(defn divisible-by? [num div] (zero? (mod num div)))
(defn fizz? [num] (divisible-by? num 3))
(defn buzz? [num] (divisible-by? num 5))
(defn fizzbuzz? [num] (and (fizz? num) (buzz? num)))
(defn ->word [num]
(cond
(fizzbuzz? num) "fizzbuzz"
(fizz? num) "fizz"
(buzz? num) "buzz"
:else num))
(defn fizzbuzz [num]
(->> (range 1 (inc num))
(map ->word)))
There might be some more I could do but for right now, I’m liking how fizzbuzz
looks right now.
Best,
Merl