Python的KeyError的惯用语Clojure版本

时间:2012-05-03 17:07:36

标签: python clojure idioms

如何表达这个python

gl_enums = ... # map from name to values for opengl enums
# use with gl_enums["enum name"]
在clojure中?这有效,但是对吗?

(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)

编辑:为了澄清,这个问题是关于抛出异常的部分,而不是地图定义部分

2 个答案:

答案 0 :(得分:4)

您的原始示例没问题。您可能会遇到两种方法:

;; 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)))))

More on clojure.core/if-let More on clojure.core/contains?

答案 1 :(得分:-1)

只需使用常规的hashmap:

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

如果您不想提供关键字(例如:keyword)但更喜欢字符串,则需要在(get gl-enums str)中使用gl-enum