Created
July 23, 2021 13:44
-
-
Save JohnnyJayJay/367f84e95b43d6d154a9e4f78f7fc50e to your computer and use it in GitHub Desktop.
Macro that can be used for small in-place tests and documentation
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
(defmacro examples | |
"Macro to generate illustrative tests for a function based on input-output pairs. | |
`f` is the function to test. | |
`equals` is the function used to compare the expected and actual result. | |
Each example call is a sequence where the first n - 1 items are the inputs and the last item is the expected output." | |
{:style/indent 1} | |
[f equals & example-calls] | |
`(fn [] | |
~@(for [call example-calls | |
:let [in (drop-last call) | |
out (last call)]] | |
`(is (~equals (~f ~@in) ~out))))) | |
;; Example usage | |
(defn rotate | |
"Rotates the given collection by n elements." | |
{:test (examples rotate = | |
[[1 2 3 4 5], 2 #_=> [4 5 1 2 3]] | |
[[], 42 #_=> []] | |
[[13 21 65 32 7], 0 #_=> [13 21 65 32 7]] | |
[[1 2 3 4 5], -2 #_=> [3 4 5 1 2]])} | |
[coll n] | |
(let [rotate-left? (neg? n) | |
left (if rotate-left? drop take-last) | |
right (if rotate-left? take drop-last)] | |
(concat (left n coll) (right n coll))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment