mapcat使用地图和concat

Ced*_*tin 7 reduce concat clojure map

为了更好地理解mapcat,我举了一个例子:

user>  (mapcat #(list % %) [1 2 3])
(1 1 2 2 3 3)
Run Code Online (Sandbox Code Playgroud)

并尝试重现文档描述的用途,故意,地图连接:

user> (doc mapcat)
clojure.core/mapcat
([f & colls])
  Returns the result of applying concat to the result of applying map
  to f and colls.  Thus function f should return a collection.
Run Code Online (Sandbox Code Playgroud)

通过做这个:

user>  (concat (map #(list % %) [1 2 3]))
((1 1) (2 2) (3 3))
Run Code Online (Sandbox Code Playgroud)

但是你可以看到它不起作用.但是,我可以像这样使用reduce,但不知道它是否正确:

user>  (reduce #(concat %1 %2) (map #(vec (list % %)) [1 2 3]))
(1 1 2 2 3 3)
Run Code Online (Sandbox Code Playgroud)

上面的工作,但我不知道这是一个正确的方法来重新创建,使用mapconcat,mapcat做什么.

基本上我想了解mapcat的工作原理.

发生了什么,我如何访问mapcat的源代码?(我正在使用Emacs + nrepl)

Kyl*_*yle 6

user=> (source mapcat)
(defn mapcat
  "Returns the result of applying concat to the result of applying map
  to f and colls.  Thus function f should return a collection."
  {:added "1.0"}
  [f & colls]
    (apply concat (apply map f colls)))
nil
user=> 
Run Code Online (Sandbox Code Playgroud)

原因reduce也有效,因为它有效:

(concat (concat '(1 1) '(2 2)) '(3 3))
Run Code Online (Sandbox Code Playgroud)

apply,在源代码中使用,扩展为:

(concat '(1 1) '(2 2) '(3 3))
Run Code Online (Sandbox Code Playgroud)

在您的初始尝试中concat:

  user=> (map #(list % %) [1 2 3])
  ((1 1) (2 2) (3 3))
  user=> (concat (list '(1 1) '(2 2) '(3 3)))
  ((1 1) (2 2) (3 3))
  user=> (concat [1])
  (1)
Run Code Online (Sandbox Code Playgroud)

您可以看到,如果concat使用单个参数调用,则返回该参数.