Difference between elements in vec<f64>


I have a vector of f64 values. Does anyone know how I can produce a vector of the differences between adjacent values ?


If I have [2, 4, 6, 10, 14, 15] it would produce


I presume I use Zip but can’t seem to get it right.


1 Like

You can zip it with an iterator over the same vector that skips the first item:



Great. Thanks

If you’re ok working with slices, can also try the windows() method:

some_slice.windows(2).map(|w| w[1] - w[0])

@vitalyd ninja’d :frowning:

1 Like

Why wouldn't they be? Vecs can be sliced trivially, by just prepending an &
(Or was that a rhetorical question?)

fn main() {
    let some_vec = vec![2, 4, 6, 10, 14, 15];
    let result = &some_vec.windows(2).map(|w| w[1] - w[0]).collect::<Vec<_>>();
    println!("{:?}", result); // [2, 2, 4, 4, 1]

I meant windows() locks you in to using only slices (and whatever can be coerced to one) whereas zip can work with any iterator.

And to be precise, you don’t need to coerce the Vec manually - my_vec.windows(2)... already does the coercion (ie the dot operator).


Ah, of course! Thanks!

(This has gotten me wondering why windows isn't implemented as an iterator adapter itself... should be possible with a circular buffer or something...)

This might not be the real reason, but it would require dynamic allocation to generically implement on all iterators.

Yeah, I was just coming to the same conclusion;
(I love it when this forum is faster at typing than my brain is at thinking :slight_smile: )

Also seems that we already have the iterator adapter in itertools::tuple_windows(), which clones all the values.

tuple_windows clones the iterator elements so that they can be part of successive windows, this makes it most suited for iterators of references and other values that are cheap to copy.

(:heart: All the excellent forumites here make it so hard to be helpful; by the time I’ve worked through a problem I’m trying to be helpful on, I’m usually already ninja’d twice by other even-more-helpful people, who provide even-better-solutions. Frustrating! :stuck_out_tongue: :heart: )


Also seems that we already have the iterator adapter in itertools::tuple_windows(), which clones all the values.

Sorry for derailing a bit, but that reminds me, is Rust planning on adding const-generics any time soon? [T; N] is currently being implemented in tons of projects with macro hacks up to [T; 32] or something like that, which is nowhere near ideal.

1 Like

Yes it’s planned but sounds like it’ll be next year for stable and maybe towards the end of this year in nightly.


Not to derail further, but same goes for generic type constructors, which will make streaming iterators possible with clean code (which is what you need in the other thread to borrow from the iterator when returning a result).