如何表达这个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)
编辑:为了澄清,这个问题是关于抛出异常的部分,而不是地图定义部分
答案 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)))))
答案 1 :(得分:-1)
只需使用常规的hashmap:
(def gl-enums {:name1 "value1", :name2 "value2",
:name3 "value3", ...})
如果您不想提供关键字(例如:keyword
)但更喜欢字符串,则需要在(get gl-enums str)
中使用gl-enum