Is the a function that essentially does foldr but witha stopping condition?

What I essentially want to do is keep folding an array from left to right with an operator, and then stopping what I hit a total so some number X.

for example:
foldl(+,[1,2,3,4,5,6],10)
I expect the results to be 10, or true. Basically anything that lets me know that somewhere in my fold I found the number 10.

Is there anything function currently in Julia that operates like this?

Sounds like your best option might just be a for loop. You could make foldl_special that does this with one pretty easily.

1 Like

Yeah I can manage it on my own, I was just curious if anything had the functionality already built in.

Not as far as Iā€™m aware. I might be wrong though.

You can do

julia> foldl(right, Scan(+) |> ReduceIf(>=(10)), [1, 2, 2, 6, 7])
11

julia> foldl(right, Map(x -> @show x) |> Scan(+) |> Map(sum -> @show sum) |> ReduceIf(>=(10)), [1, 2, 2, 6, 7])
x = 1
sum = 1
x = 2
sum = 3
x = 2
sum = 5
x = 6
sum = 11
11

with https://github.com/tkf/Transducers.jl

5 Likes