Please consider the following list data
. I was trying to accumulate data
until the result turns positive the first time and finally found an approach. Maybe it's useful to others and maybe there are other (more efficient) approaches:
data={-1050, 50, 1001, 1950, 1950, 1950, 525, 0};
The same what Accumulate
does can be done by FoldList
:
Rest@FoldList[Plus, 0, data] == Rest@FoldList[#1 + #2 &, 0, data] == Accumulate@data
(*True*)
Now, one can add constraints to FoldList
. For my problem I had to write:
Rest[FoldList[If[#1 + #2 < #2, #1 + #2, #2] &, 0, #]]&@data
(*{-1050, -1000, 1, 1950, 1950, 1950, 525, 0}*)
Question
How can this be improved, either in terms of speed or elegance?
If[#1 < 0, #1, 0] + #2 &
. The versions usingBoole[]
orUnitStep[]
seemed a bit slower in my tests; someone might want to do more testing on those. $\endgroup$LengthWhile
orTakeWhile
to obtain that output from the full list. $\endgroup$FoldList
is only there to describe how I got to the last code-line. The most crucial point to me was to formulate an alternative toAccumulate
with the addition of implementingconditions
. $\endgroup$