#Iterator nesting precedence of Chain and Copied

10 messages · Page 1 of 1 (latest)

wooden ocean
#

Even though this is perhaps a really minor detail, I was wondering whether the following type signature I had previously written, was the better choice of two potential options, whether in terms of brevity, performance, or pragmatics:

These are implementation details within a (currently hidden) module of a crate I am working on, so even though it would be marked pub in either case, neither version would be directly user-facing, if that makes any difference.

Original:

pub struct Iter<'a>(
    std::iter::Copied<
        std::iter::Chain<std::slice::Iter<'a, usize>, std::option::Iter<'a, usize>>>,
);

Is it somehow more natural to write it as the following:

pub struct Iter<'a>(
    std::iter::Chain<
        std::iter::Copied<std::slice::Iter<'a, usize>>, 
        std::iter::Copied<std::option::Iter<'a, usize>>>,
);

tl;dr: should one distribute std::iter::Copied or other unary combinators, or wrap around std::iter::Chain and other binary combinators?

late rover
#

in terms of code readability, the first is IMO better since it has fewer pieces — hopefully in the future we will have type-alias-impl-trait and not have to write such awkward signatures in the first place

#

in terms of performance they are very likely to be identical once optimized, but if you care about such small differences you should benchmark the different versions

#

the first might be be slightly faster to compile since the compiler only has to monomorphize one copy of Copied, not two, that way

honest chasm
#

i think it would become equally good if you used Chain, Copied and Iter

#

but the first one is nicer since it's shorter

late rover
#

can't use Iter since there are two different Iters involved

honest chasm
#

ah right, but at least use std::{iter::{Chain, Copied}, option, slice};

tame gull
#

Also, you can as them

#
use std::{
  iter::{Chain, Copied}, 
  option::Iter as OptionIter, 
  slice::Iter as SliceIter,
};
```Although whether this is better is admittedly questionable