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