Created
May 20, 2018 15:18
-
-
Save stuarthalloway/6fb3c4f155242e2eb94f4a3060528bab to your computer and use it in GitHub Desktop.
Alternate approach to http://johannes.tax/Inline_unit_tests_in_Clojure.html
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
(defn round5 | |
"Round to the closest positive multiple of 5. | |
Negative numbers round to 0, which is not | |
considered a multiple of 5." | |
{:test (fn [] (let [roundsto (fn [e] #(= e (round5 %)))] | |
(testing "Negative numbers" | |
(is (every? (roundsto 0) (range -20 0)))) | |
(testing "Positive numbers rounding to 5" | |
(is (every? (roundsto 5) (range 0 8)))) | |
(testing "Positive numbers rounding not to 5" | |
(is (every? (roundsto 10) (range 8 13))) | |
(is (every? (roundsto 20) (range 18 23))) | |
(is (= 1020 (round5 1022))))))} | |
[n] | |
(cond (< n 0) | |
0 | |
(< n 8) | |
5 | |
:else | |
(let [remainder (rem n 5) | |
quotient (quot n 5)] | |
(* 5 (+ quotient | |
(if (<= remainder 2) | |
0 | |
1)))))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment