meander

All things about https://github.com/noprompt/meander Need help and no one responded? Feel free to ping @U5K8NTHEZ
markaddleman 2020-08-05T19:28:21.310300Z

I needed a simple template system. I think this fits the bill for both simple and easy:

(m/rewrite {:keys     #{::name ::state}
              :template ["here is some data for" ::name
                         {:name  ::name
                          :state ::state}]
              :values   {::name  "Mark"
                         ::state "California"}}
    {:keys     ?keys
     :values   ?values
     :template (m/$ ?ctx (m/pred (partial contains? ?keys) ?key))}
    (m/cata {:keys     ?keys, :values ?values
             :template (m/app ?ctx (m/app ?values ?key))})

    {:template ?result} ?result)

noprompt 2020-08-06T16:58:40.310400Z

Another tool you can use for this (not Meander) is clojure.walk/prewalk-replace:

(let [bindings {::name "Mark"
                ::state "California"}
      template ["here is some data for"
                ::name
                {:name  ::name
                 :state ::state}]]
  (clojure.walk/prewalk-replace bindings template))
;; =>
["here is some data for" "Mark" {:name "Mark", :state "California"}]

noprompt 2020-08-06T17:03:27.310600Z

Of course, if you don’t want something as blunt as prewalk-replace you can accomplish the same thing with Meander and your own custom rules for more control:

(let [bindings {::name "Mark"
                ::state "California"}
      template ["here is some data for"
                ::name
                {:name  ::name
                 :state ::state}]]
  (m/rewrite [template bindings]
    [[!xs ...] ?bindings]
    [(m/cata [!xs ?bindings]) ...]

    [{?k ?v & ?rest} ?bindings]
    {(m/cata [?k ?bindings]) (m/cata [?v ?bindings]) & (m/cata [?rest ?bindings])}

    [?x {?x ?v :as ?bindings}]
    (m/cata [?v ?bindings])
    
    ?x
    ?x))
;; =>
["here is some data for" "Mark" {:state "California", :name "Mark"}]

👍 1