Python的KeyError的惯用Clojure版本
作者:互联网
这个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)
编辑:为澄清起见,此问题与引发异常的部分有关,而不是与地图定义的部分有关
解决方法:
您最初的示例是可以的.您也可能会遇到两种方法:
;; 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?
标签:clojure,idioms,python 来源: https://codeday.me/bug/20191201/2080356.html