I have a generator which yields state, weight
pairs. The type of state
is not known in advance. I would like to collect enough state
s so that the sum of weight
s is at least S
. I prefer to utilize the nice “narrowest type” machinery of collect
to do this, so that the resulting vector has the narrowest type.
Two-pass implementation MWE (note that here of course the type of states is known, but let’s pretend it isn’t):
function collect_upto(f, S)
result = Any[]
s = zero(S)
while s ≤ S
x, w = f()
s += w
push!(result, x)
end
collect(result)
end
collect_upto(()->(rand(),rand(1:10)), 100)
Is it possible to do this in a single pass without writing a custom iterator (which seems overkill)?