Idiomatic version of Clojure Python version KeyError

How should this python be expressed

gl_enums = ... # map from name to values for opengl enums
# use with gl_enums["enum name"]

in clojure? It works, but right?

(def gl-enums ...) ; map from name to values for opengl enums
(defn gl-enum [k] (or (gl-enums k) (throw (SomeException.))))
; use with (gl-enum :enum-name)

edit: for clarification, this question is about the exception throwing part, not the map defining part

+3
source share
2 answers

Your original example is fine. You may also come across two approaches:

;; not very idiomatic
(defn example
  [m]
  (if (contains? m :name)
    (:name m)
    (throw (IllegalArgumentException. (format "key %s is missing" :name)))))

;; idiomatic
(defn example
  [m]
  (if-let [v (:name m)]
    v
    (throw (IllegalArgumentException. (format "key %s is missing" :name)))))

Learn more about clojure.core / if-let Learn more about clojure.core / contains?

+4
source

Just use a regular hash file:

(def gl-enums {:name1 "value1", :name2 "value2",
               :name3 "value3", ...})

if you do not want to provide keywords (e.g. :keyword), but prefer strings, you need to use (get gl-enums str)ingl-enum

-1
source

All Articles