有沒有一種更優雅的方式讓into
可以處理單個項目和列表,而不是以下(無可否認的殘酷)功能?將單身和名單放入clojure列表中
(defn into-1-or-more
[this-list list-or-single]
(into this-list (flatten (conj [] list-or-single))))
,它可以處理兩種:
(into-1-or-more [1 2 3 4] 5)
;[1 2 3 4 5]
或者:
(into-1-or-more [1 2 3 4] [5 6 7 8])
;[1 2 3 4 5 6 7 8]
我建立一個收集與降低使用into []
在列表從函數的結果。但是,某些功能會返回單個項目,而其他功能會返回項目列表。像:
(reduce #(into [] (% data)) [func-return-item func-return-list func-return-either])
最好的解決方案是隻做下面的代替嗎?
(into [] (flatten (map #(% data) [func-return-item ...])
如果沒有必要,我會避免使用'reduce','reduce'不是懶惰,'map'就是。 – Marcs
在這種特殊情況下,所有數據都被消耗掉了。儘管你當然是對的。 –
也看看https://stuartsierra.com/2015/06/10/clojure-donts-heisenparameter – OlegTheCat