Skip to content
Browse files

get-in support for default #256

Signed-off-by: Stuart Halloway <stu@thinkrelevance.com>
  • Loading branch information...
1 parent 59ecee6 commit c19ce8145053578763ac3bef4de9d8c3c44e1b11 @timothypratley timothypratley committed with stuarthalloway Jan 30, 2010
Showing with 39 additions and 4 deletions.
  1. +9 −4 src/clj/clojure/core.clj
  2. +30 −0 test/clojure/test_clojure/data_structures.clj
View
13 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
View
30 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))))
+

0 comments on commit c19ce81

Please sign in to comment.
Something went wrong with that request. Please try again.