Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

if key exists: update, otherwise: assoc

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?

like image 852
Anton Harald Avatar asked Feb 11 '16 00:02

Anton Harald


2 Answers

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

(update m k (fnil conj []) v)
like image 150
Daniel Compton Avatar answered Nov 06 '22 00:11

Daniel Compton


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.

like image 31
notan3xit Avatar answered Nov 06 '22 00:11

notan3xit