Created
February 20, 2013 14:08
-
-
Save thheller/4995766 to your computer and use it in GitHub Desktop.
Split a vector into a map of vectors
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
(defn split-into-map [items key-fn] | |
(when-not (key-fn (first items)) | |
(throw (ex-info "first item is not a key" {:items items}))) | |
(loop [result {} | |
current-parts [] | |
items items] | |
(let [item (first items)] | |
(cond | |
(and (nil? item) (empty? items)) | |
(assoc result (first current-parts) (vec (rest current-parts))) | |
(key-fn item) | |
(recur (if (seq current-parts) | |
(assoc result (first current-parts) (vec (rest current-parts))) | |
result) | |
[item] | |
(rest items)) | |
:else | |
(recur result (conj current-parts item) (rest items)) | |
)))) | |
(prn (split-into-map [:key1 1 2 3 :key2 4 :key3 5 6 7] keyword?)) | |
(prn (split-into-map ["y" 1 2 "x" 3 4 5] string?)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment