Mercurial > rlm
view src/rlm/map_utils.clj @ 6:b8bbb0dbda7b
merging
author | Robert McIntyre <rlm@mit.edu> |
---|---|
date | Thu, 01 Mar 2012 05:55:59 -0700 |
parents | 78a630e650d2 |
children |
line wrap: on
line source
1 (ns rlm.map-utils2 "A lot of times you want to transform maps by some function3 that operates only on their keys or values, but then get a4 map object back again. This makes that sort of thing easier."5 ^{:author "Robert McIntyre"}6 (:use [rlm7 [dreams :only [defn-decorated]]8 [decorators :only [preserve-meta]]]))11 (defn map-keys12 "Transform a map by applying a function to its keys13 and \"dragging along\" its values. the transformation14 function must be one-to-one for the keys of the map15 and its range or else the resulting map would have more than16 one value for a key"17 [f m]18 (zipmap (map f (keys m)) (vals m)))20 (defn map-vals21 "Transform a map by applying a function to its values, keeping the22 keys the same."23 [f m]24 (zipmap (keys m) (map f (vals m))))27 (defn filter-keys28 "Makes a new map which contains only pairs for which29 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-vals35 "Makes a new map which contains only pairs for which36 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-by42 "returns a new sorted map using the provided function as a comparator43 the comparator function takes two KEYS and compares them"44 [fn map]45 (into (sorted-map-by fn ) map))47 (defn def-map48 "takes a map and creates in the current namespace symbols49 corresponding to its keys with values corresponding to its50 values. If the symbols already exist, it just overwrites them.51 Great for debugging at the REPL because you can just define a test52 map, then establish all the key-val variables, then copy snippets53 from a function which references a map in this way and directly test54 the code with those values."55 [])