Last active
September 17, 2015 12:04
-
-
Save alandipert/ad45716353df8e78b8c1 to your computer and use it in GitHub Desktop.
Enumerate paths into a nested map
This file contains hidden or 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
;; Copyright (c) Alan Dipert. All rights reserved. | |
;; The use and distribution terms for this software are covered by the | |
;; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) | |
;; By using this software in any fashion, you are agreeing to be bound by | |
;; the terms of this license. | |
;; You must not remove this notice, or any other, from this software. | |
(defn paths | |
"Enumerate paths into a nested map." | |
([root] | |
(when (map? root) | |
(paths [] root))) | |
([parent x] | |
(if (map? x) | |
(mapcat (fn [[k v]] (paths (conj parent k) v)) x) | |
[parent]))) | |
(def m | |
{:q {:z 1} | |
:x {:y {:a 1} | |
:b {:b 2}}}) | |
(paths m) ;=> ([:q :z] [:x :y :a] [:x :b :b]) | |
(reduce #(update-in %1 %2 dec) m (paths m)) | |
;=> {:q {:z 0}, :x {:y {:a 0}, :b {:b 1}}} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment