gpt4 book ai didi

mapcat 使用 map 和 concat

转载 作者:行者123 更新时间:2023-12-04 11:41:00 25 4
gpt4 key购买 nike

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

user>  (mapcat #(list % %) [1 2 3])
(1 1 2 2 3 3)

并试图重现文档描述的内容,故意使用 map 和 concat :
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.

通过做这个:
user>  (concat (map #(list % %) [1 2 3]))
((1 1) (2 2) (3 3))

但是,如您所见,它不起作用。但是,我可以像这样使用 reduce,但不知道它是否正确:
user>  (reduce #(concat %1 %2) (map #(vec (list % %)) [1 2 3]))
(1 1 2 2 3 3)

以上方法有效,但我不知道这是否是使用 map 和 concat 重新创建 mapcat 的正确方法。

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

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

最佳答案

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=>

原因 reduce 也有效是因为它有效:
(concat (concat '(1 1) '(2 2)) '(3 3))

apply ,如源代码中所用,扩展为:
(concat '(1 1) '(2 2) '(3 3))

在您初次尝试 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)

你可以看到,如果你调用 concat使用单个参数,它返回该参数。

关于mapcat 使用 map 和 concat,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13224733/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com