if key exists: update, otherwise: assoc
Asked Answered
S

2

13

consider this inside a reduce loop:

(if (contains? m k)
  (update m k conj v)
  (assoc m k [v]))

Is there a way to get rid of the if statement?

Sierrasiesser answered 11/2, 2016 at 0:29 Comment(0)
H
23

Use fnil to handle the nil value of v when k doesn't exist in the map:

(update m k (fnil conj []) v)
Heimer answered 11/2, 2016 at 0:37 Comment(2)
took me some time to grasp it, but yes! got it now, great answer!Sierrasiesser
shazam, nice answer!Keli
A
3

While the fnil answer is more spectacular, I find the following easier to read, especially if unfamiliar with fnil:

(assoc m k (conj (m k []) v))

where (m k []) returns the value of k in m or defaults to [] if k does not exist in m.

If k is a symbol, (k m []) would also work.

Accordant answered 9/11, 2017 at 14:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.