Mercurial > rlm
diff src/rlm/map_utils.clj @ 0:78a630e650d2
initial import
author | Robert McIntyre <rlm@mit.edu> |
---|---|
date | Tue, 18 Oct 2011 00:57:08 -0700 |
parents | |
children |
line wrap: on
line diff
1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000 1.2 +++ b/src/rlm/map_utils.clj Tue Oct 18 00:57:08 2011 -0700 1.3 @@ -0,0 +1,55 @@ 1.4 +(ns rlm.map-utils 1.5 + "A lot of times you want to transform maps by some function 1.6 + that operates only on their keys or values, but then get a 1.7 + map object back again. This makes that sort of thing easier." 1.8 + ^{:author "Robert McIntyre"} 1.9 + (:use [rlm 1.10 + [dreams :only [defn-decorated]] 1.11 + [decorators :only [preserve-meta]]])) 1.12 + 1.13 + 1.14 +(defn map-keys 1.15 + "Transform a map by applying a function to its keys 1.16 + and \"dragging along\" its values. the transformation 1.17 + function must be one-to-one for the keys of the map 1.18 + and its range or else the resulting map would have more than 1.19 + one value for a key" 1.20 + [f m] 1.21 + (zipmap (map f (keys m)) (vals m))) 1.22 + 1.23 +(defn map-vals 1.24 + "Transform a map by applying a function to its values, keeping the 1.25 + keys the same." 1.26 + [f m] 1.27 + (zipmap (keys m) (map f (vals m)))) 1.28 + 1.29 + 1.30 +(defn filter-keys 1.31 + "Makes a new map which contains only pairs for which 1.32 + the filter function on the key of the pair returns true." 1.33 + [fun m] 1.34 + (select-keys m (filter fun (keys m)))) 1.35 + 1.36 + 1.37 +(defn filter-vals 1.38 + "Makes a new map which contains only pairs for which 1.39 + the filter function on the value of the pair returns true." 1.40 + [fun m] 1.41 + (into {} (filter (comp fun val) m))) 1.42 + 1.43 + 1.44 +(defn sort-map-by 1.45 + "returns a new sorted map using the provided function as a comparator 1.46 + the comparator function takes two KEYS and compares them" 1.47 + [fn map] 1.48 + (into (sorted-map-by fn ) map)) 1.49 + 1.50 +(defn def-map 1.51 + "takes a map and creates in the current namespace symbols 1.52 + corresponding to its keys with values corresponding to its 1.53 + values. If the symbols already exist, it just overwrites them. 1.54 + Great for debugging at the REPL because you can just define a test 1.55 + map, then establish all the key-val variables, then copy snippets 1.56 + from a function which references a map in this way and directly test 1.57 + the code with those values." 1.58 + [])