How to parse a string into a list of floats using a functional style?

I am trying to parse a string in a list of floating point values ​​in Rust. I would suggest that there is a smart way to do this with iterators and Option s; however, I cannot make it ignore Err values ​​that are the result of failed parse () calls. The Rust tutorial does not seem to cover any examples like this, and the documentation is confusing at best.

How can I implement this using vector / list operations of a functional style? Pointers to the best rust style for my iterative implementation will also be appreciated!

"Functional" style

Panic when he meets Err

 input.split(" ").map(|s| s.parse::<f32>().unwrap()).collect::<Vec<_>>() 

iterative style

Ignores non-floating values ​​as implied

 fn parse_string(input: &str) -> Vec<f32> { let mut vals = Vec::new(); for val in input.split_whitespace() { match val.parse() { Ok(v) => vals.push(v), Err(_) => (), } } vals } fn main() { let params = parse_string("1 -5.2 3.8 abc"); for &param in params.iter() { println!("{:.2}", param); } } 
+7
functional-programming rust
source share
1 answer

filter_map does what you want by converting the values ​​and filtering out None s:

 input.split(" ").filter_map(|s| s.parse::<f32>().ok()).collect::<Vec<_>>(); 

Note the ok method to convert Result to Option .

+8
source share

All Articles