Reputation: 241
I'm trying to learn clojure.
I am calling a function which is returning me an array of strings..
If I do:
(let [items (get-all-items)]
(println (type items))
(items))
the type
of items
is shown as class clojure.lang.PersistentVector
where as the items
value is like so:
[["Dogs"] ["Cats"] ["Capybaras"] ["Pygmy Hedgehogs"]]
I would like to convert this to a map in a format like this:
{ "Dogs" "Cats" "Capybaras" "Pygmy Hedgehogs" }
Does that make sense? Clojure maps can contain list of strings right?
I am only doing this because if I have it as a map, I can check if I have a pet in the list like this:
(contains? pets "Dogs")
; assuming the map is stored in pets variable
that fails if pets
is a vector.
So If I can convert that to maps, how do I convert it? if not, how do I search for something in the vector?
(I like working with maps so I'd rather have maps - unless there is a strong reason not to do so)
ps: I've tried converting with into but that doesn't work either.
Upvotes: 3
Views: 1651
Reputation: 31621
I suspect what you really want is a set, not a map. Maps store a value associated with a specific key. Sets store a unique list of values.
If your only use case is testing for membership, then you definitely want a set. You want a map if you are also associating some data with that key.
It's very easy to produce a set from any sequence. In your case:
(set (flatten items))
;;=> #{"Pygmy Hedgehogs" "Dogs" "Cats" "Capybaras"}
flatten
removes the nesting on your lists giving you a sequence of strings. set
consumes the sequence and returns a set of the unique values in that sequence.
Upvotes: 3
Reputation: 34800
(apply assoc {} (flatten [["Dogs"] ["Cats"] ["Capybaras"] ["Pygmy Hedgehogs"]]))
;;=> {"Capybaras" "Pygmy Hedgehogs", "Dogs" "Cats"}
Upvotes: 3