You're viewing version 1.2.0 of get-in. The latest stable version of Clojure Core is 1.3.0.
1.2.0 Arrow_down_16x16

get-in

clojure.core

  • (get-in m ks)
  • (get-in m ks not-found)
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.

3 Examples top

  • ;; We can use get-in for reaching into nested maps:
    user=> (def m {:username "sally"
                   :profile {:name "Sally Clojurian"
                             :address {:city "Austin" :state "TX"}}})
    #'user/m
    
    user=> (get-in m [:profile :name])
    "Sally Clojurian"
    user=> (get-in m [:profile :address :city])
    "Austin"
    user=> (get-in m [:profile :address :zip-code])
    nil
    user=> (get-in m [:profile :address :zip-code] "no zip code!")
    "no zip code!"
    
    
    ;; Vectors are also associative:
    user=> (def v [[1 2 3]
                   [4 5 6]
                   [7 8 9]])
    #'user/v
    user=> (get-in v [0 2])
    3
    user=> (get-in v [2 1])
    8
    
    
    ;; We can mix associative types:
    user=> (def mv {:username "jimmy"
                    :pets [{:name "Rex"
                            :type :dog}
                           {:name "Sniffles"
                            :type :hamster}]})
    #'user/mv
    user=> (get-in mv [:pets 1 :type])
    :hamster
    
  • (def s1 [[:000-00-0000 "TYPE 1" "JACKSON" "FRED"]
             [:000-00-0001 "TYPE 2" "SIMPSON" "HOMER"]
             [:000-00-0002 "TYPE 4" "SMITH" "SUSAN"]])
    
    (def cols [0 2 3])
    
    (defn f1 
      [s1 col] 
      (map #(get-in s1 [% col] nil) (range (count s1))))
    
    (apply interleave (map (partial f1 s1) cols))
    
    (:000-00-0000 "JACKSON" "FRED" :000-00-0001 "SIMPSON" "HOMER" :000-00-0002 "SMITH" "SUSAN")
  • ;; spam link removed
Log in to add / edit an example.

See Also top

Log in to add a see also.

Plus_12x12 Minus_12x12 Source clojure/core.clj:4921 top

(defn get-in
  "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."
  {:added "1.2"}
  ([m ks]
     (reduce get m ks))
  ([m ks not-found]
     (loop [sentinel (Object.)
            m m
            ks (seq ks)]
       (if ks
         (let [m (get m (first ks) sentinel)]
           (if (identical? sentinel m)
             not-found
             (recur sentinel m (next ks))))
         m))))
Vars in clojure.core/get-in: defn get identical? let loop next reduce
Used in 0 other vars

Comments top

No comments for get-in. Log in to add a comment.