Skip to content

Instantly share code, notes, and snippets.

Created September 28, 2009 02:31
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 anonymous/195087 to your computer and use it in GitHub Desktop.
Save anonymous/195087 to your computer and use it in GitHub Desktop.
user> (defn assoc-with
"Associates a value in a nested associative structure, where ks is a
sequence of keys and v is the new value and returns a new nested structure."
[m [fn & fns] v]
(let [val (or (fn m) [])]
(if fns
(replace {val (assoc-with val fns v)} m)
(replace {val v} m))))
#'user/assoc-with
user> (assoc-with [1 2 [[3 4 5]]] [last first last] 6)
[1 2 [[3 4 6]]]
user> (defn update-with
"'Updates' a value in a nested associative structure, where fns is a
sequence of fns and f is a function that will take the old value
and any supplied args and return the new value, and returns a new
nested structure."
([m [fn & fns] f & args]
(let [val (or (fn m) [])]
(if fns
(replace {val (apply update-with val fns f args)} m)
(replace {val (apply f val args)} m)))))
#'user/update-with
user> (update-with [1 2 [[3 4 5]]] [last first] conj 6)
[1 2 [[3 4 5 6]]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment