# Terminate in collect

**URL:** <https://discourse.julialang.org/t/terminate-in-collect/3022>\
**Category:** General Usage\
**Tags:** question\
**Created:** [April 3, 2017, 11:51am UTC](https://discourse.julialang.org/t/terminate-in-collect/3022 "2017-04-03T11:51:25Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Tamas\_Papp](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/tamas_papp/32/25949_2.png) [@Tamas\_Papp](https://discourse.julialang.org/u/Tamas_Papp)\
**Post date:** [April 3, 2017, 11:51am UTC](https://discourse.julialang.org/t/terminate-in-collect/3022/1 "2017-04-03T11:51:25Z")

</div>

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):

```julia
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)?

---

<div class="post-metadata">

**Author:** ![yuyichao](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/yuyichao/32/20_2.png) [@yuyichao](https://discourse.julialang.org/u/yuyichao)\
**Post date:** [April 3, 2017, 12:46pm UTC](https://discourse.julialang.org/t/terminate-in-collect/3022/2 "2017-04-03T12:46:54Z")

</div>

For implementation, [https://github.com/JuliaLang/julia/blob/ceb06740e307a8b2d43f3480efaa33311a90f021/base/array.jl#L426](https://github.com/JuliaLang/julia/blob/ceb06740e307a8b2d43f3480efaa33311a90f021/base/array.jl#L426)  
You can also create a filter iterator/comprehension but it can be non-trivial given your function has side effect and the termination condition does not only depend on current element.
