-
-
Save sandrovicente/cd32aeac76bf8f842d2cc507db96df1e to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#![feature(slice_patterns)] | |
use itertools::Itertools; | |
use std::collections::HashMap; | |
#[derive(Debug, PartialEq, Eq, Hash)] | |
enum Kind { Zero, Five, Other } | |
fn main() { | |
let sts = ["aqui", "e", "o", "gato"].iter().map(|&x| String::from(x)).collect::<Vec<_>>(); | |
let les = sts.iter().map(|x| x.len()).collect::<Vec<_>>(); | |
let z = sts.iter().zip(les.iter()).collect::<Vec<_>>(); | |
println!("z>> {:?}", z); | |
//let gz = z.into_iter().group_by(|zi| zi.1).collect::<HashMap<_,_>>(); | |
// group data into runs of larger than zero or not. | |
let data = vec![1, 3, -2, -2, 1, 0, 1, 2, -2, 0]; | |
// groups: |---->|------>|--------->| | |
// Note: The `&` is significant here, `GroupBy` is iterable | |
// only by reference. You can also call `.into_iter()` explicitly. | |
for (key, group) in &data.into_iter().group_by(|elt| *elt >= 0) { | |
// Check that the sum of each group is +/- 4. | |
//assert_eq!(4, group.sum::<i32>().abs()); | |
println!("{:?}, {:?}", key, group.into_iter().collect::<Vec<i32>>()); | |
} | |
let values = 0..6; // Not inclusive. | |
let cycling = values.cycle(); | |
// Group them into a HashMap. | |
let grouped = cycling.take(20).map(|x| { | |
// Return a tuple matching the (key, value) desired. | |
match x { | |
x if x == 5 => (Kind::Five, 5), | |
x if x == 0 => (Kind::Zero, 0), | |
x => (Kind::Other, x), | |
} | |
// Accumulate the values | |
}).fold(HashMap::<Kind, Vec<_>>::new(), |mut acc, (k, x)| { | |
acc.entry(k).or_insert(vec![]).push(x); | |
acc | |
}); | |
println!("{:?}", grouped); | |
let mut a = HashMap::<u32, Vec<u32>>::new(); | |
a.entry(3).or_insert(vec![]).push(4); | |
println!("{:?}", a); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment