Skip to content

Instantly share code, notes, and snippets.

@alandipert
Last active September 17, 2015 12:04
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save alandipert/ad45716353df8e78b8c1 to your computer and use it in GitHub Desktop.
Save alandipert/ad45716353df8e78b8c1 to your computer and use it in GitHub Desktop.
Enumerate paths into a nested map
;; 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