Clojure: reduce, reductions and infinite lists

前端 未结 4 529
陌清茗
陌清茗 2020-12-15 08:57

Reduce and reductions let you accumulate state over a sequence. Each element in the sequence will modify the accumulated state until the end of the sequence is reached.

4条回答
  •  爱一瞬间的悲伤
    2020-12-15 09:35

    If you want to keep getting items from a list like an IO stream and keep state between runs, you cannot use doseq (without resorting to def's). Instead a good approach would be to use loop/recur this will allow you to avoid consuming too much stack space and will let you keep state, in your case:

     (loop [c (cycle [0])]
       (if (evaluate-some-condition (first c))
         (do-something-with (first c) (recur (rest c)))
         nil))
    

    Of course compared to your case there is here a condition check to make sure we don't loop indefinitely.

提交回复
热议问题