Vec::interpose?

interpose([a, b, c], x) -> [a, x, b, x, c]

I have an implementation as follows. Is there a builtin for this?

pub fn interpose<T: Clone>(t: T, data: Vec<T>) -> Vec<T> {
    let mut ans = Vec::<T>::new();
    match data.first() {
        None => {
            return ans;
        }
        Some(f) => {
            ans.push(f.clone());
            for x in data.iter().skip(1) {
                ans.push(t.clone());
                ans.push(x.clone());
            }
            return ans;
        }
    }
}

The itertools crate provides an intersperse adaptor that does this for any iterator, not just Vec.

1 Like