Hi Timothy,
On Feb 2, 1:19 am, Timothy Pratley <[email protected]> wrote:
> There are still some sharp edges I'm not sure about:
> (A) user=> (get-in {:a 1} [])
> {:a 1}
> ;; this is existing behavior, but I feel the result should be nil
+1 for nil
> (B) user=> (get-in {:a 1} nil)
> {:a 1}
> ;; this is existing behavior, but I feel the result should be nil (nil
> is a seq so not an exception)
+1 for nil
> (C) user=> (get-in {:a 1} 5)
> java.lang.IllegalArgumentException: Don't know how to create ISeq
> from: java.lang.Integer (NO_SOURCE_FILE:0)
> ;; existing behavior, seems sensible to throw an exception here rather
> than return nil
+1 for exception
> (D) user=> (get-in {nil {:a 1}} [] 2)
> {:a 1}
> ;; new behavior
> ;; using last/butlast only -> this is wrong... need to check the seq size
> ;; the solution depends upon what is correct for the preceding cases
> so need to establish those first
>
> Alternatively one could take the view that [] and nil are illegal key
> sequences, in which case should get-in enforce that (via preconditions
> or just a check) or should it just be added to the doc-string that
> using those values is undefined, or both?
I'm not sure about this too. I tend to an exception. (get m) will also
throw an exception...
> For reference here is a version that behaves most like existing get-in:
>
> (defn get-in
> "Returns the value in a nested associative structure,
> where ks is a sequence of keys. Returns nil if the key is not present,
> or the not-found value if supplied."
> ([m ks]
> (reduce get m ks))
> ([m ks not-found]
> (if (empty? ks)
> m
> (if-let [l (reduce get m (butlast ks))]
> (get l (last ks) not-found)
> not-found))))
I would get rid of the if-let. Together with throwing an exception in
case of an empty key sequence we get:
(defn get-in
"Returns the value in a nested associative structure,
where ks is a sequence of keys. Returns nil if the key is not
present,
or the not-found value if supplied."
([m ks] (get-in m ks nil))
([m ks not-found]
(if-let [ks (seq ks)]
(get (reduce get m (butlast ks)) (last ks) not-found)
(throw (Exception. "key sequence must not be empty")))))
Sincerely
Meikel
--
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To post to this group, send email to [email protected]
Note that posts from new members are moderated - please be patient with your
first post.
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/clojure?hl=en