min-key

clojure.core

  • (min-key k x)
  • (min-key k x y)
  • (min-key k x y & more)
Returns the x for which (k x), a number, is least.

2 Examples top

  • ;; we have a list of key colours
    ;; We want to find the one closest to a supplied colour
    ;; We're storing rgb values as [r g b]
    ;; use min-key to find colour that minimizes 
    ;; the euclidean distance between the supplied colour 
    ;; and each key colour
    ;; thanks to rhudson, raek and mfex on #clojure
    
    (defn distance-squared [c1 c2]
      "Euclidean distance between two collections considered as coordinates"
      (->> (map - c1 c2) (map #(* % %)) (reduce +)))
    
    (def key-colours
         {[224 41 224] :purple
          [24 180 46] :green
          [12 129 245] :blue
          [254 232 23] :yellow
          [233 233 233] :white
          [245 27 55] :red
          [231 119 41] :orange
          })
    
    (defn rgb-to-key-colour
      "Find colour in colour map closest to the supplied [r g b] triple"
      [rgb-triple colour-map]
      (colour-map
       (apply min-key (partial distance-squared rgb-triple) (keys colour-map))))
    
    user=> (rgb-to-key-colour [255 0 0] key-colours)
    :red
    
  • ; "min-key"/"max-key" to "min"/"max" like "sort-by" to "sort"
    (min-key #(Math/abs %) -3 1 4)
    ; 1
    
    (apply min-key #(Math/abs %) [-3 1 4])
    ; 1
    
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:4404 top

(defn min-key
  "Returns the x for which (k x), a number, is least."
  {:added "1.0"
   :static true}
  ([k x] x)
  ([k x y] (if (< (k x) (k y)) x y))
  ([k x y & more]
   (reduce1 #(min-key k %1 %2) (min-key k x y) more)))
Vars in clojure.core/min-key:
Used in 0 other vars

Comments top

No comments for min-key. Log in to add a comment.