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

Clojure map a set to another set directly?

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

有没有办法将一个函数应用到一个集合,然后 return 直接应用到一个集合?

正如 Alex 所说,algo.generic 中的 fmap 提供了此功能,尽管如果您查看源代码,它的功能与您的代码完全相同。我建议只将您的函数放在代码中的 util 命名空间中,这可能不值得为一个函数引入整个库。

使用 Clojure 1.7.0(仍处于测试阶段),您可以使用转换器执行此操作:

(into #{} (map inc) #{1 2 3})

一种稍微更通用的方法是使用 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