user=> (map inc #{1 2 3})
(2 4 3)
user=> (into #{} (map inc #{1 2 3}))
#{4 3 2}
有没有办法将函数应用于集合并直接返回集合?
答案 0 :(得分:1)
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.
答案 1 :(得分:1)
With Clojure 1.7.0 (still in beta) you can do this using a transducer:
ionic start blank
答案 2 :(得分:1)
稍微更通用的方法是使用empty
:
(defn my-map [f c]
(into (empty c)
(map f c)))
这产生以下结果:
(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)
它也适用于其他persistent collections。