Last active
December 15, 2015 21:29
-
-
Save prepor/5326359 to your computer and use it in GitHub Desktop.
Clojure pattern matching and tests. See https://github.com/clojure/core.match/wiki/Overview
This file contains hidden or 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
| (deftest match-t | |
| (let [v {:foo 1 :bar 100}] | |
| (is (match? v {:foo 1 :bar (_ :guard integer?)})))) | |
| (import | |
| '[java.util Date]) | |
| (defn timestamp | |
| [] | |
| (-> (Date.) | |
| (.getTime) | |
| (/ 1000) | |
| int)) | |
| (defn like-timestamp? | |
| [v] | |
| (let [t (timestamp)] | |
| (< (- t 10) v (+ t 10)))) | |
| (def user-tasks #{1 5}) | |
| (deftest match-complex-t | |
| (let [result {:user 1 | |
| :projects ["mnemoniq"] | |
| :tasks [1 5] | |
| :created-at (timestamp)}] | |
| (is (match? result ({:user (_ :guard integer?) | |
| :projects (projects :guard [vector? #(= 1 (count %))]) | |
| :tasks tasks | |
| :created-at (_ :guard like-timestamp?)} | |
| :only [:user :projects :tasks :created-at]) | |
| (is (every? #(contains? user-tasks %) tasks)))))) |
This file contains hidden or 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
| (use '[clojure.core.match :only (match)]) | |
| (defmethod assert-expr 'match? [msg form] | |
| (let [[_ value pattern & body] form] | |
| `(let [result# (match ~value | |
| ~pattern (do ~@body :success) | |
| :else :fail)] | |
| (if (= :success result#) | |
| (do-report {:type :pass, :message ~msg, | |
| :expected '~form, :actual ~value}) | |
| (do-report {:type :fail, :message ~msg, | |
| :expected '~form, :actual ~value})) | |
| result#))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment