In Clojure, second argument in map-indexed
SPOILER ALERT:这是关于4Clojure问题157(索引序列)的答案。
这个问题的快速版本:在
Indexing Sequences #157
Transform a sequence into a sequence of pairs containing the original elements along with their index.
1
2
3 (= (__ [:a :b :c]) [[:a 0] [:b 1] [:c 2]])
(= (__ [0 1 3]) '((0 0) (1 1) (3 2)))
(= (__ [[:foo] {:bar :baz}]) [[[:foo] 0] [{:bar :baz} 1]])
我很快就找到了答案:
由用户tomdmitriev。
问题:第二个论点从何而来?
那么,对于
地图索引状态的文档:
Returns a lazy sequence consisting of the result of applying f to 0
and the first item of coll, followed by applying f to 1 and the second
item in coll, etc, until coll is exhausted. Thus function f should
accept 2 arguments, index and item. Returns a stateful transducer when
no collection is provided. -- my emphasis
好吧,我也只提供了一个论点,即4Clojure问题的集合。 我不确定这是如何工作的...是否存在某种隐式或隐式参数?
感谢您为清除此问题提供的帮助!
传递给map-indexed的函数是[index item]的函数。 易于理解:
1 2 | (map-indexed (fn [idx itm] [idx itm])"item") ; ([0"item"]) |
它实际上是一个apply_map_with_index
回到您的示例,使用:
1 2 | (map-indexed #(vector %2 %1) [:a :b :c]) ; ([:a 0] [:b 1] [:c 2]) |
将创建一小段向量,由%2项,%1索引组成。
您还可以将以上内容与易于理解的内容进行比较:
1 2 | (map-indexed #(vector %1 %2) [:a :b :c]) ; ([0 :a] [1 :b] [2 :c]) |
它创建一个[index item]的小向量序列。
编辑:
如果我们分两步进行分解,则得到:
1 2 3 4 5 6 7 8 9 10 | ; we need to define a function ; with two parameters (defn my-function [index item] (vector item index)) ; map-indexed uses a function with ; two parameters (map-indexed my-function [:a :b :c]) |