Fork me on GitHub
#beginners
<
2016-07-08
>
arijun17:07:38

is there a function to hash-map as set is to hash-set?

seancorfield17:07:05

@arijun: How would you convert an arbitrary collection into a map?

seancorfield17:07:29

If you have a sequence of pairs, you can use (into {} seq-of-pairs)

seancorfield17:07:57

Ah, then (apply hash-map [k1 v1 k2 v2]) will work.

arijun17:07:57

why make the choice in one case but be unwilling to in the other?

seancorfield17:07:30

You can convert an arbitrary collection into a set, but only certain shapes of collection can make a valid map.

seancorfield17:07:20

If you have an even number of items in your collection, apply hash-map will work. If you have an odd number of items, you’ll get an error. If you have a collection of pairs, into {} will work.

seancorfield17:07:37

(into {} [[k1 v1] [k2 v2]])

arijun18:07:54

oh yeah that's actually the way I have it

arijun18:07:01

thanks sean

arijun18:07:47

it seems weird that there is no symmetric rountrip capability (unlike, say (set (vec s))) . Worrying about errors doesn't seem sensible since the other methods will also give you an error with malformed input. I feel like it's probably just because the name map was already taken.

seancorfield18:07:43

No, it wouldn’t make sense: as shown above, there are two representations that can be used to construct hash maps.

seancorfield18:07:12

It’s also reflected in reduce and reduce-kv — hash maps are "special" collections.

seancorfield18:07:59

(the latter works on associative collections so it works on vectors too — but you need to understand the abstractions behind the collection types)

seancorfield18:07:35

Also consider that you can’t round-trip through a set: (vec (set v)) will not necessarily give you the original back.