rlm@0
|
1 (ns rlm.map-utils
|
rlm@0
|
2 "A lot of times you want to transform maps by some function
|
rlm@0
|
3 that operates only on their keys or values, but then get a
|
rlm@0
|
4 map object back again. This makes that sort of thing easier."
|
rlm@0
|
5 ^{:author "Robert McIntyre"}
|
rlm@0
|
6 (:use [rlm
|
rlm@0
|
7 [dreams :only [defn-decorated]]
|
rlm@0
|
8 [decorators :only [preserve-meta]]]))
|
rlm@0
|
9
|
rlm@0
|
10
|
rlm@0
|
11 (defn map-keys
|
rlm@0
|
12 "Transform a map by applying a function to its keys
|
rlm@0
|
13 and \"dragging along\" its values. the transformation
|
rlm@0
|
14 function must be one-to-one for the keys of the map
|
rlm@0
|
15 and its range or else the resulting map would have more than
|
rlm@0
|
16 one value for a key"
|
rlm@0
|
17 [f m]
|
rlm@0
|
18 (zipmap (map f (keys m)) (vals m)))
|
rlm@0
|
19
|
rlm@0
|
20 (defn map-vals
|
rlm@0
|
21 "Transform a map by applying a function to its values, keeping the
|
rlm@0
|
22 keys the same."
|
rlm@0
|
23 [f m]
|
rlm@0
|
24 (zipmap (keys m) (map f (vals m))))
|
rlm@0
|
25
|
rlm@0
|
26
|
rlm@0
|
27 (defn filter-keys
|
rlm@0
|
28 "Makes a new map which contains only pairs for which
|
rlm@0
|
29 the filter function on the key of the pair returns true."
|
rlm@0
|
30 [fun m]
|
rlm@0
|
31 (select-keys m (filter fun (keys m))))
|
rlm@0
|
32
|
rlm@0
|
33
|
rlm@0
|
34 (defn filter-vals
|
rlm@0
|
35 "Makes a new map which contains only pairs for which
|
rlm@0
|
36 the filter function on the value of the pair returns true."
|
rlm@0
|
37 [fun m]
|
rlm@0
|
38 (into {} (filter (comp fun val) m)))
|
rlm@0
|
39
|
rlm@0
|
40
|
rlm@0
|
41 (defn sort-map-by
|
rlm@0
|
42 "returns a new sorted map using the provided function as a comparator
|
rlm@0
|
43 the comparator function takes two KEYS and compares them"
|
rlm@0
|
44 [fn map]
|
rlm@0
|
45 (into (sorted-map-by fn ) map))
|
rlm@0
|
46
|
rlm@0
|
47 (defn def-map
|
rlm@0
|
48 "takes a map and creates in the current namespace symbols
|
rlm@0
|
49 corresponding to its keys with values corresponding to its
|
rlm@0
|
50 values. If the symbols already exist, it just overwrites them.
|
rlm@0
|
51 Great for debugging at the REPL because you can just define a test
|
rlm@0
|
52 map, then establish all the key-val variables, then copy snippets
|
rlm@0
|
53 from a function which references a map in this way and directly test
|
rlm@0
|
54 the code with those values."
|
rlm@0
|
55 [])
|