Hi guys, I have a sequence that is a struct where I have a starting value, a delta and a repeat, as in
pub struct Sequence {
start: u32,
delta: u32,
repeat: u32,
}
what I want to do is that given a vector of number, I can convert that into a vector of Sequence. Examples:
- [1, 2, 3, 4] corresponds to the following sequence
Sequence {
start= 1,
delta: 1,
repeat: 3,
}
- [1, 2, 3, 5] corresponds to 2 sequences
Sequence {
start= 1,
delta: 1,
repeat: 2,
}
Sequence {
start= 5,
delta: 0,
repeat: 0,
}
Now, I know how to do this the old way with while cycles and stuff.. I was experimenting a little bit around fold, reduce and I came up with an implementation (that doesn't work)
pub fn generate_sequences(from: Vec<u32>) -> Vec<Sequence> {
if from.is_empty() {
return Vec::new();
}
let mut sequences = Vec::new();
let mut last_sequence = Sequence::new(from[0], 0, 0);
let res = from.into_iter().fold(last_sequence, |mut seq, next| {
let delta = next - seq.start;
let res = match seq.delta {
0 => {
seq.delta = delta;
seq.repeat = 1;
seq
}
_ if seq.delta == delta => {
seq.repeat = seq.repeat + 1;
seq
}
_ => {
sequences.push(seq);
Sequence::new(next, 0, 0)
}
};
res
});
sequences.push(res);
sequences
}
}
The implementation above doesn't work because the iter starts with the first item (so I count the first guy twice), so probably fold isn't the right operation here. I wonder if there is an idiomatic way of doing this in rust (my implementation is pretty ugly even if it would have worked )?