clojure - 'get' replacement that throws exception on not found? -


i'd access values in maps , records, throwing exception when key isn't present. here's i've tried. there better strategy?

this doesn't work because throw evaluated every time:

(defn get-or-throw-1 [rec key]   (get rec key (throw (exception. "no value.")))) 

maybe there's simple method using macro? well, isn't it; has same problem first definition, if evaluation of throw happens later:

(defmacro get-or-throw-2 [rec key]   `(get ~rec ~key (throw (exception. "no value.")))) 

this 1 works letting get return value (in theory) never generated other way:

(defn get-or-throw-3 [rec key]   (let [not-found-thing :i_would_never_name_some_thing_this_021138465079313         value (get rec key not-found-thing)]     (if (= value not-found-thing)         (throw (exception. "no value."))         value))) 

i don't having guess keywords or symbols never occur through other processes. (i use gensym generate special value of not-found-thing, don't see why better. don't have worry intentionally trying defeat purpose of function using value of not-found-thing in map or record.)

any suggestions?

this find function for: (find m k) returns nil if nothing found, or [k v] if mapping k v found. can distinguish these two, , don't need guess @ might in map. can write:

(defn strict-get [m k]   (if-let [[k v] (find m k)]     v     (throw (exception. "just leave me alone!")))) 

Comments

Popular posts from this blog

javascript - RequestAnimationFrame not working when exiting fullscreen switching space on Safari -

Python ctypes access violation with const pointer arguments -