Improve pattern for finite-length iterators in flat_map expansions #116

Open
opened 2020-08-06 16:55:10 +00:00 by gburd · 0 comments
gburd commented 2020-08-06 16:55:10 +00:00 (Migrated from github.com)

There are a bunch of places where we want to turn a collection of tuples (like Vec<(A, B, C)>) into a flat iterator, like A1, B1, C1, A2, B2, C2, .... The pattern we're using right now is to combine flat_map and std::iter::once, like:

collection.flat_map(|(a, b)| once(a).chain(once(b)))

That avoids heap allocation in favour of stack allocation, but gets pretty gnarly when the tuple length increases. For example:

This ticket tracks doing something better. Perhaps a few helper functions (like once_2 and once_3?), or impl (A, B) { fn once(...) { } }, or a macro to at least make the callsite easier to read.

This is probably not a good first bug unless you're strong in Rust, because some taste is required to determine what's better than the pattern we have now.

There are a bunch of places where we want to turn a collection of tuples (like `Vec<(A, B, C)>`) into a flat iterator, like `A1, B1, C1, A2, B2, C2, ...`. The pattern we're using right now is to combine `flat_map` and `std::iter::once`, like: ```rust collection.flat_map(|(a, b)| once(a).chain(once(b))) ``` That avoids heap allocation in favour of stack allocation, but gets pretty gnarly when the tuple length increases. For example: - https://github.com/mozilla/mentat/pull/214/files/64ff2efe012bb4297056c5899076af0c7f4ca49d#diff-54794907269c3b2d0bebbfd6a8aeab5dR617 - https://github.com/mozilla/mentat/pull/214/files/64ff2efe012bb4297056c5899076af0c7f4ca49d#diff-54794907269c3b2d0bebbfd6a8aeab5dR476 This ticket tracks doing something better. Perhaps a few helper functions (like `once_2` and `once_3`?), or `impl (A, B) { fn once(...) { } }`, or a macro to at least make the callsite easier to read. This is probably not a good first bug unless you're strong in Rust, because some taste is required to determine what's _better_ than the pattern we have now.
Sign in to join this conversation.
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set.

Reference: greg/mentat#116
No description provided.