Clojure将一组映射到另一组直接?

时间:2015-05-12 21:56:35

标签: clojure

user=> (map inc #{1 2 3})
(2 4 3)
user=> (into #{} (map inc #{1 2 3}))
#{4 3 2}

有没有办法将函数应用于集合并直接返回集合?

3 个答案:

答案 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