首页 > 其他分享 >rust group

rust group

时间:2022-08-15 17:22:14浏览次数:46  
标签:mut group self let vec data MyGroupBy rust

use std::fmt::Debug;

#[derive(Debug)]
struct MyData<T:Clone>{
    data: Vec<T>
}
impl<T:Clone+Debug> MyData<T> {
    fn group_by<F>(&self, pred: F)->MyGroupBy<T, F>
    where F: FnMut(&T,&T) ->bool
    {
        MyGroupBy { data: self.data.clone(), predicate: pred }
    }
}

struct MyGroupBy<T:Debug, P>{
    data: Vec<T>,
    predicate: P
}

impl<T:Clone+Debug, P> Iterator for MyGroupBy<T, P> 
where
    P: FnMut(&T, &T) -> bool
{
    type Item = Vec<T>;
    fn next(&mut self) -> Option<Self::Item> {
        if self.data.is_empty(){
            None
        }else{
            let mut len = 1;
            let mut iter = self.data.windows(2);
            while let Some([l,r]) = iter.next(){
                if (self.predicate)(l, r) { len += 1 } else { break }
            }
            let tmp = self.data.clone();
            let (head, tail) = tmp.split_at(len);
            self.data = tail.to_vec();
            Some(head.to_vec())
        }
    }
}

impl<T:Debug, P> std::fmt::Debug for MyGroupBy<T, P> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("GroupBy").field("slice", &self.data).finish()
    }
}

fn main () {
    let xx = vec![vec![1,2,3], vec![1,2,5], vec![2,3,5], vec![2,3,1]];
    let myd = MyData{ data:xx };
    let mut it = myd.group_by(|a, b|a[0]==b[0]).collect::<Vec<Vec<Vec<i32>>>>();
    println!("{:?}", it);
    // for i in it{
    //     println!("{:?}", i);
    // }
}

  

标签:mut,group,self,let,vec,data,MyGroupBy,rust
From: https://www.cnblogs.com/pythonClub/p/16588978.html

相关文章

  • rust f64 比较
      (val1-val2).abs()<f64::EPSILON  val1.to_ne_bytes()==val2.to_ne_bytes()或者 val1.to_bits()==val2.to_bits()......
  • RUST基础:变量遮蔽
    Rust基础入门书籍推荐《深入浅出RUST》Rust是允许在同一个代码块中声明同样名字的变量。如果这样做,后面声明的变量会将前面声明的变量“遮蔽(Shadowing)”起来。如:1fnm......
  • react+rust+webAssembly(wasm)示例
    前言:WebAssembly(简称wasm)已经出来有几年了,在一些需要高性能的web应用场景中,wasm技术可以让代码执行效率大大提升。react做为目前大厂主流的前端框架之一,搭配上最近几年一......
  • Spark中group_concap替换函数concat_ws,collect_set-实现数分组后,将分组后字段连接排序
    group_concat可以在mysql中group_concat(distinctpap_srcorderbydata_date)hive中group_concat函数只能分组后连接起来,不能orderbydata_date排序spark中用conca......