任意数量的集合上的map-indexed函数

时间:2016-02-29 15:02:39

标签: clojure

在Clojure中有一个map-indexed函数(但是版本" 1.8.0"),它只接受最多两个参数(source):

由于我看不出任何理由不拥有任意数量的参数,我正在尝试编写自己的版本(重用现有的map-indexed函数):

(defn map-index
  "like clojure.core/map-indexed but accepts more than two arguments"
  ([f] ;;(partial (map f (range))) ;; TODO transducer ?
   )
  ([f coll] (map f (range) coll))
  ([f c1 c2] (map f (range) c1 c2))
  ([f c1 c2 c3] (map f (range) c1 c2 c3))
  ([f c1 c2 c3 & colls]
   ;; Warning !
   ;; calling map-indexed with a final parameter freezes my REPL
   (map f (conj colls c3 c2 c1 (range)))))


((map-indexed list) ["a" "b" "c"])
(map-indexed list ["a" "b" "c"])

((map-index list) ["a" "b" "c"]) ;; KO

(map-index list ["a" "b" "c"])
(map-index list ["a" "b" "c"] ["d" "e" "f"]) ;; OK
(map-index list ["a" "b" "c"] ["d" "e" "f"]  ["g" "h" "i"]) ;; OK
(map-index list ["a" "b" "c"] ["d" "e" "f"]  ["g" "h" "i"] ["k" "l" "m"]) ;; freezes the REPL

我该如何写这个map-index函数?

1 个答案:

答案 0 :(得分:2)

我会这样写:

(defn map-index
  ([f]
   (map-indexed f))
  ([f & colls]
   (apply map f (range) colls)))

除非你真的关心性能,否则不需要使用额外的arities过度复杂化。

值得注意的是,由于此处的传感器版本只是调用map-indexed,因此它不会为任意数量的集合工作。如果您需要这样做,我会留给您实施。