summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorTimothy Pratley <timothypratley@gmail.com>2010-01-30 14:32:43 +1100
committerStuart Halloway <stu@thinkrelevance.com>2010-06-07 10:03:25 -0400
commitc19ce8145053578763ac3bef4de9d8c3c44e1b11 (patch)
treed778ca2813dbbe677665a44ff988d3ad787aba64
parent59ecee6a6f037612b3b1ed2d939f5e0017f2dd11 (diff)
get-in support for default #256
Signed-off-by: Stuart Halloway <stu@thinkrelevance.com>
-rw-r--r--src/clj/clojure/core.clj13
-rw-r--r--test/clojure/test_clojure/data_structures.clj30
2 files changed, 39 insertions, 4 deletions
diff --git a/src/clj/clojure/core.clj b/src/clj/clojure/core.clj
index 11800ead..ca615435 100644
--- a/src/clj/clojure/core.clj
+++ b/src/clj/clojure/core.clj
@@ -4907,10 +4907,15 @@
;;;;;;;;;;;;; nested associative ops ;;;;;;;;;;;
(defn get-in
- "returns the value in a nested associative structure, where ks is a sequence of keys"
- {:added "1.0"}
- [m ks]
- (reduce get m ks))
+ "Returns the value in a nested associative structure,
+ where ks is a sequence of ke(ys. Returns nil if the key is not present,
+ or the not-found value if supplied."
+ ([m ks]
+ (reduce get m ks))
+ ([m ks not-found]
+ (if (seq ks)
+ (get (reduce get m (butlast ks)) (last ks) not-found)
+ m)))
(defn assoc-in
"Associates a value in a nested associative structure, where ks is a
diff --git a/test/clojure/test_clojure/data_structures.clj b/test/clojure/test_clojure/data_structures.clj
index ee4fd41a..0ea8deca 100644
--- a/test/clojure/test_clojure/data_structures.clj
+++ b/test/clojure/test_clojure/data_structures.clj
@@ -517,6 +517,35 @@
{} {:a 1 :b 2}
#{} #{1 2} ))
+(deftest test-get
+ (let [m {:a 1, :b 2, :c {:d 3, :e 4}, :f nil, :g false, nil {:h 5}}]
+ (is (thrown? IllegalArgumentException (get-in {:a 1} 5)))
+ (are [x y] (= x y)
+ (get m :a) 1
+ (get m :e) nil
+ (get m :e 0) 0
+ (get m :b 0) 2
+ (get m :f 0) nil
+
+ (get-in m [:c :e]) 4
+ (get-in m '(:c :e)) 4
+ (get-in m [:c :x]) nil
+ (get-in m [:f]) nil
+ (get-in m [:g]) false
+ (get-in m [:h]) nil
+ (get-in m []) m
+ (get-in m nil) m
+
+ (get-in m [:c :e] 0) 4
+ (get-in m '(:c :e) 0) 4
+ (get-in m [:c :x] 0) 0
+ (get-in m [:b] 0) 2
+ (get-in m [:f] 0) nil
+ (get-in m [:g] 0) false
+ (get-in m [:h] 0) 0
+ (get-in m [:x :y] {:y 1}) {:y 1}
+ (get-in m [] 0) m
+ (get-in m nil 0) m)))
;; *** Sets ***
@@ -798,3 +827,4 @@
(range 1 6) (-> EMPTY
(into (range 7))
pop))))
+