【问题标题】:In Clojure, second argument in map-indexed在 Clojure 中,map-indexed 中的第二个参数
【发布时间】:2016-01-29 02:10:37
【问题描述】:

剧透警告:这是关于4Clojure question 157 的答案,索引序列。

这个问题的快速版本:在(map-indexed #(vector %2 %1) [:a :b :c])中,%2是什么?

索引序列 #157

将序列转换为包含原始元素及其索引的对序列。

(= (__ [: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]])

我很快找到了答案:#(map reverse (map-indexed vector %)),但看到了似乎更好的答案,例如:

map-indexed #(vector %2 %1)

用户tomdmitriev

问题:第二个参数从何而来?

那么,对于(map-indexed #(vector %2 %1) [:a :b :c])%2 是什么?

docs for map-indexed 状态:

返回一个惰性序列,该序列由将 f 应用于 0 的结果组成 和 coll 的第一项,然后将 f 应用于 1 和第二项 coll 等中的项目,直到 coll 用完。因此 函数 f 应该 接受 2 个参数,索引和项目。 不提供集合。 -- 我的重点

好吧,我也只提供了一个论点,即来自 4Clojure 问题的集合。我不确定这是如何工作的……是否存在某种隐含或隐含的论点?

感谢您帮助解决这个问题!

【问题讨论】:

    标签: clojure


    【解决方案1】:

    传递给map-indexed 的函数是[index item] 的函数。易于理解:

     (map-indexed (fn [idx itm] [idx itm]) "item")
     ; ([0 "item"])
    

    其实是一个apply_map_with_index

    回到你的例子,用:

     (map-indexed #(vector %2 %1) [:a :b :c])
     ; ([:a 0] [:b 1] [:c 2])
    

    将创建一个小的向量序列,由 %2 项和 %1 索引组成。

    你也可以对比一下上面的通俗易懂的:

     (map-indexed #(vector %1 %2) [:a :b :c])
     ; ([0 :a] [1 :b] [2 :c])
    

    创建[索引项]的小向量序列。

    编辑:

    如果我们分两步分解它,它会给出:

      ; 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])
    

    【讨论】:

    • 谢谢,也许我明白了。那么,简单地说,我们为函数提供了它的第二个参数(集合),而map-indexed 本身提供了第一个参数(索引)?
    • 没有。 map-indexed 需要一个双参数函数作为第一个参数,一个集合作为第二个参数。地图索引然后在集合的每个项目上“循环”。
    • 啊,现在我明白了。您在此处的评论和您回答中的编辑很好地清除了它,谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-04
    • 1970-01-01
    • 1970-01-01
    • 2017-12-12
    • 2013-07-06
    • 2012-01-23
    相关资源
    最近更新 更多