As part of on API I am working on, one of the higher-level functions collects results from an iterative algorithm. The results use user-defined functions, which are ideally type stable, but don’t have to be. Code could look like
""" get_result(state) Return the result from state. Defined by the user. """ function get_result end """ update_state(rng, state) Return a new state updated randomly. Uses user-defined components. """ function update_state(rng, state) end function collect_results(state, N, rng = Base.Random.GLOBAL_RNG) results = FIXME_initialize(...) for _ in 1:N FIXME_add!(results, get_result(state)) state = update_state(rng, state) end results end
FIXME is where I need help.
I could somehow cram this into a form for
collect with closures, but I would prefer to keep the loop. Looking at the sources, the internals of
collect have mechanisms for initializing a container with a type, then dealing with the possibility of getting something else instead. Is there a chance of using those? An example would help.
Ideally, my hope is that the compiler can sometimes figure out types for
get_result, then it would be nice to get efficient code, but that’s a best case scenario I would not want to rely on, and want the right container type even if that does not work.