爲了更好地理解會員名:mapcat我花了一個例子:會員名:mapcat使用地圖和CONCAT
user> (mapcat #(list % %) [1 2 3])
(1 1 2 2 3 3)
並試圖重現什麼文檔描述了使用上的目的,地圖和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))
但是,正如你所看到的,它不起作用。不過,我可以用減少這樣的,但不知道這是否是正確的:
user> (reduce #(concat %1 %2) (map #(vec (list % %)) [1 2 3]))
(1 1 2 2 3 3)
上述作品,但我不知道這是否是重新建立一個正確的方式,使用地圖和CONCAT什麼mapcat呢。
基本上我想了解mapcat在引擎蓋下工作。
這是怎麼回事,我怎樣才能訪問mapcat的來源? (我使用Emacs + nrepl)
使用'apply'可能比'reduce'更好,因爲'reduce'會爲每對參數做'concat'。由於'concat'是懶惰的,當這些值實際上被強制的時候,你最終會得到一個_really_深度調用堆棧,可能會導致堆棧溢出。 [這是一個簡單的例子。](https://www.refheap.com/paste/6409) – DaoWen
只是一個提示 - 在使用'reduce'實現時,不需要將'concat'包裝在匿名函數中。這也可以工作:'(reduce concat(map ...))'並且更好,因爲它更好地處理空輸入的情況。 – Alex