On Wed, Jun 1, 2011 at 1:05 AM, Andreas Kostler
<[email protected]> wrote:
> Hi all,
> I find myself using the following pattern quite often:
> (assoc m :key (inc (or (:kay m) 0))
>
> To increment or somehow transform a value in a map that I'm not sure it
> exists.
> Is there an idiomatic way of doing this sort of thing in a short and concise
> way?
Well, these also work:
(assoc m :key (inc (m :key 0)))
(merge-with + m {:key 1})
(update-in m [:key] #(if % (inc %) 1))
The merge-with looks shortest and cleanest of the four to me, but
that's just my opinion.
Incidentally, if you forget the brackets around :key in the update-in
the error message you get is rather less specific than you'd hope:
=> (update-in {:a 1} :key #(do (println %) (inc %)))
#<CompilerException java.lang.UnsupportedOperationException: nth not
supported on this type: Keyword (NO_SOURCE_FILE:0)>
A :pre clause in update-in checking for coll? on the second argument
could be added to produce an IAE with a more informative message
instead of this somewhat vague UOE.
--
Protege: What is this seething mass of parentheses?!
Master: Your father's Lisp REPL. This is the language of a true
hacker. Not as clumsy or random as C++; a language for a more
civilized age.
--
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