view src/clojure/contrib/map_utils.clj @ 10:ef7dbbd6452c

added clojure source goodness
author Robert McIntyre <rlm@mit.edu>
date Sat, 21 Aug 2010 06:25:44 -0400
parents
children
line wrap: on
line source
1 ;; Copyright (c) Jason Wolfe. All rights reserved. The use and
2 ;; distribution terms for this software are covered by the Eclipse Public
3 ;; License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) which can
4 ;; be found in the file epl-v10.html at the root of this distribution. By
5 ;; using this software in any fashion, you are agreeing to be bound by the
6 ;; terms of this license. You must not remove this notice, or any other,
7 ;; from this software.
8 ;;
9 ;; map_utils.clj
10 ;;
11 ;; Utilities for operating on Clojure maps.
12 ;;
13 ;; jason at w01fe dot com
14 ;; Created 25 Feb 2009
16 (ns
17 ^{:author "Jason Wolfe, Chris Houser",
18 :doc "Utilities for operating on Clojure maps."}
19 clojure.contrib.map-utils)
22 (defmacro lazy-get
23 "Like get, but doesn't evaluate not-found unless it is needed."
24 [map key not-found]
25 `(if-let [pair# (find ~map ~key)]
26 (val pair#)
27 ~not-found))
29 (defn safe-get
30 "Like get, but throws an exception if the key is not found."
31 [map key]
32 (lazy-get map key
33 (throw (IllegalArgumentException. (format "Key %s not found in %s" key map)))))
35 (defn safe-get-in
36 "Like get-in, but throws an exception if any key is not found."
37 [map ks]
38 (reduce safe-get map ks))
40 ; by Chouser:
41 (defn deep-merge-with
42 "Like merge-with, but merges maps recursively, applying the given fn
43 only when there's a non-map at a particular level.
45 (deepmerge + {:a {:b {:c 1 :d {:x 1 :y 2}} :e 3} :f 4}
46 {:a {:b {:c 2 :d {:z 9} :z 3} :e 100}})
47 -> {:a {:b {:z 3, :c 3, :d {:z 9, :x 1, :y 2}}, :e 103}, :f 4}"
48 [f & maps]
49 (apply
50 (fn m [& maps]
51 (if (every? map? maps)
52 (apply merge-with m maps)
53 (apply f maps)))
54 maps))