How to make a cumulative sequence?

大憨熊 提交于 2019-12-08 14:42:25

问题


Say I have a lazy sequence like the following:

(def s (iterate inc 1))
(take 10 s)
=> (1 2 3 4 5 6 7 8 9 10)

Now, I want to generate a sequence of cumulative sum of s like the following:

=> (1 3 6 10 15 ...)

How can I do this? What I tried is to use atom and accumulate the sum to it(mutating) Is this the only way to generate cumulative sequence or is there a better way to do this?

NOTE: the above cumulative sum is only an example. The source sequence can be other sequence. So I can't use formula: s(n) = n(n+1)/2


回答1:


(take 10 (reductions + s))
=> (1 3 6 10 15 21 28 36 45 55)


来源:https://stackoverflow.com/questions/14754706/how-to-make-a-cumulative-sequence

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!