`conj` into maps

110 views
Skip to first unread message

Chas Emerick

unread,
Nov 7, 2011, 10:42:10 PM11/7/11
to Clojure
From[1]:

conj expects another (possibly single entry) map as the item, and returns a new map which is the old map plus the entries from the new, which may overwrite entries of the old.

=> (conj {:a 5} {:b 6})
{:b 6, :a 5}

This doesn't make much sense to me; it seems that the values one can add to a map should be limited to map entries / vector pairs, if for no other reason than to correspond with the the "granularity" of values in sequences obtained from maps:

=> (first (seq {:a 5}))   ;; a vector / map entry
[:a 5]

I can't remember ever seeing conj used to add all the entries of a map (or, maps) to another map in the wild; that's what `merge` is for, after all.

I wonder if this is vestigial.  FWIW, APersistentMap.cons(Object)[2] checks for the value being consed as a map entry and as a vector before getting around to the case where it can be a seqable of map entries.  Also, this behaviour of conj w.r.t. maps seems to make `merge` redundant:

=> (merge {:a 5} {:b 5} {:c 5} {:d 7})
{:d 7, :c 5, :b 5, :a 5}
=> (conj {:a 5} {:b 5} {:c 5} {:d 7})
{:d 7, :c 5, :b 5, :a 5}

I feel like I may have known of the rationale for this being as it is at some point, but perhaps I've forgotten now. :-)  Can anyone remind me?

Thanks,

- Chas

Stuart Sierra

unread,
Nov 9, 2011, 8:28:49 AM11/9/11
to clo...@googlegroups.com
It may relate to the implementation of IPersistentCollection.cons(Object).

As far as I know, the IPersistentCollection.cons(Object) method powers the polymorphic behavior of the `conj` function, and is the foundation for the persistent collections in general.

-S

Chas Emerick

unread,
Nov 9, 2011, 10:11:09 AM11/9/11
to clo...@googlegroups.com
Right, a collection can implement cons however it likes.  While it's convenient, I was just curious about the 'why' of APersistentMap's implementation, esp. since it overlaps w/ `merge`.

- Chas

--
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To post to this group, send email to clo...@googlegroups.com
Note that posts from new members are moderated - please be patient with your first post.
To unsubscribe from this group, send email to
clojure+u...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/clojure?hl=en

Stuart Sierra

unread,
Nov 9, 2011, 1:07:44 PM11/9/11
to clo...@googlegroups.com
I expect you're right: it's vestigial.
-S

Reply all
Reply to author
Forward
0 new messages