Created
September 28, 2009 02:31
-
-
Save anonymous/195087 to your computer and use it in GitHub Desktop.
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
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