Skip to content

Instantly share code, notes, and snippets.

@borkdude
Created March 12, 2021 22:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save borkdude/26906ee15585ed5e1b7a8eda4cc1ee18 to your computer and use it in GitHub Desktop.
Save borkdude/26906ee15585ed5e1b7a8eda4cc1ee18 to your computer and use it in GitHub Desktop.
Core.match like matching with malli
(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