Created
January 10, 2019 18:36
-
-
Save Vrixyz/eb42fd43a2b39a4c9ff61fb1dad4af42 to your computer and use it in GitHub Desktop.
Simple flatten
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
#[derive(Debug)] | |
enum Data<T> { | |
Value(T), | |
Array(Vec<Data<T>>), | |
} | |
impl<T> Data<T> { | |
fn flatten(self) -> Vec<T> { | |
match self { | |
Data::Value(v) => vec![v], | |
Data::Array(arr) => { | |
let mut result = vec![]; | |
for elem in arr { | |
result.append(&mut elem.flatten()); | |
} | |
result | |
} | |
} | |
} | |
} | |
fn main() { | |
let data = Data::Array(vec![ | |
Data::Value(2), | |
Data::Value(3), | |
Data::Array(vec![ | |
Data::Value(3), | |
Data::Array(vec![Data::Value(4), Data::Value(5)]), | |
]), | |
]); | |
println!("{:#?}", data.flatten()); | |
} | |
#[cfg(test)] | |
mod tests { | |
use super::*; | |
#[test] | |
fn simple() { | |
let data = Data::Value(1); | |
assert_eq!(data.flatten(), vec![1]); | |
} | |
#[test] | |
fn complex() { | |
let data = Data::Array(vec![ | |
Data::Value(1), | |
Data::Value(2), | |
Data::Value(3), | |
Data::Array(vec![ | |
Data::Value(3), | |
Data::Array(vec![Data::Value(4), Data::Value(5)]), | |
]), | |
]); | |
assert_eq!(data.flatten(), vec![1, 2, 3, 3, 4, 5]); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment