Reputation: 2355
user=> (map inc #{1 2 3})
(2 4 3)
user=> (into #{} (map inc #{1 2 3}))
#{4 3 2}
Is there a way to apply a function to a set and return a set directly?
Upvotes: 1
Views: 136
Reputation: 16095
A slightly more generic way to do this is to use empty
:
(defn my-map [f c]
(into (empty c)
(map f c)))
This yields following results:
(my-map inc #{1 2 3}) ;; => #{2 3 4}
(my-map inc [1 2 3]) ;; => [2 3 4]
(my-map inc '(1 2 3)) ;; => (4 3 2)
It would work for other persistent collections as well.
Upvotes: 1
Reputation: 2759
With Clojure 1.7.0 (still in beta) you can do this using a transducer:
(into #{} (map inc) #{1 2 3})
Upvotes: 1
Reputation: 14569
As Alex said, fmap from algo.generic provides this function, although if you look at the source it's doing exactly the same as your code. I'd recommend just putting your function in a util namespace in your code, it's probably not worth pulling in a whole library for one function.
Upvotes: 1