Use REST inside your Clojure programs. Represent an edit to a data structure as a data structure (patch) and apply it to any nested combination of maps, lists, vectors and sets.
Add this to project.clj
(if you use Leiningen)
[patcher "0.1.3"]
or this to deps.edn
(if you don't)
{patcher {:mvn/version "0.1.3"}}
First things first, let's get imports and namespaces off our chest.
(require '[patcher.core :refer [apply-patch]])
Then fire up the REPL, type a definition in-o:
(def patch {:type :put :path [:some :keys] :value "A new value"})
And apply it to a thing-o
(apply-patch patch {:some {:keys "An old value"} :other {:keys "I am a value too, y'know"}})
=> {:some {:keys "A new value"} :other {:keys "I am a value too, y'know"}}
Apply it to a thing-o
(apply-patch {:type :post :path [:interests] :value :music} {:age 35 :sex :male :interests [:cooking]})
=> {:age 35 :sex :male :interests [:cooking :music]}
A patch is a map with 3 keys: :type
, :path
and :value
. :type
can be :put
, :post
, :delete
or :merge
.
:put
will replace whatever value you would get with (get-in coll path)
with value
:post
is similar, but it will insert (conj
) value
into the existing sequence instead of replacing it
:merge
assumes that value
is a map or a sequence and replaces a map or a sequence at path
with a concatenation (merger) of it and value
:delete
will purge it from the data structure so that (get-in coll path)
returns nil
Copyright © 2018 Skolkovo Institute of Science and Technology
Distributed under the Eclipse Public License either version 1.0 or (at your option) any later version.