Created
March 12, 2021 22:57
-
-
Save borkdude/26906ee15585ed5e1b7a8eda4cc1ee18 to your computer and use it in GitHub Desktop.
Core.match like matching with malli
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
(require '[malli.core :as m]) | |
(require '[clojure.string :as str]) | |
(declare ->schema) | |
(defn variable? [x] | |
(and (simple-symbol? x) | |
(str/starts-with? (str x) "?"))) | |
(defn ->catn [pattern] | |
(into [:catn] (map (fn [elt] | |
(if (variable? elt) | |
[elt :any] | |
[(symbol (str "_" (gensym))) (->schema elt)])) pattern))) | |
(defn ->schema | |
"Coerces pattern into malli schema" | |
[pattern] | |
(cond | |
(vector? pattern) (->catn pattern) | |
:else [:= pattern])) | |
(require '[clojure.walk :as walk]) | |
(defn strip-ignored-keys [m] | |
(walk/postwalk (fn [m] | |
(if (map? m) | |
(let [ks (filter variable? (keys m))] | |
(select-keys m ks)) | |
m)) | |
m)) | |
(defn match [pattern value] | |
(-> (m/parse (->schema pattern) | |
value) | |
strip-ignored-keys)) | |
(match '[1 ?x 3] | |
[1 2 3]) ;;=> {?x 2} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment