4ZM
4ZM

Reputation: 1503

conj-ing a list of values to a map value in Clojure?

What is the idiomatic way of conj-ing a list of values to a map value?

This is the result I want, but the anonymous function looks kind of ugly imo. Is there a better way?

> (update-in {:x #{}} [:x] #(apply conj % '(1 2)))
{:x #{1 2}}

Upvotes: 3

Views: 556

Answers (2)

Thumbnail
Thumbnail

Reputation: 13473

You should not have to know whether the map contains? the key that you are conjing values to. Adapting your example ...

(update-in {} [:x] #(apply conj % '(1 2)))
;{:x (2 1)}

... not what you want.

The following

(defn assocs [m k coll]
  (assoc m k (into (get m k #{}) coll)))

... supplies an empty-set value if no entry for the key exists.

(assocs {} :x [1 2])
;{:x #{1 2}}

(assocs {:x #{2}} :x [1 2])
;{:x #{1 2}}

You'll find similar code in clojure.algo.graph, for example here. (Warning: the graph type only functions in one of the algorithms and otherwise just gets in the way.)

Upvotes: 0

A. Webb
A. Webb

Reputation: 26446

The anonymous function is unnecessary

(update-in {:x #{}} [:x] conj 1 2)
;=> {:x #{1 2}}

(update-in {:x #{}} [:x] into [1 2])
;=> {:x #{1 2}}

Upvotes: 4

Related Questions