Swapped longest into its declarative form.
The function was ment to use the functional programming style, however, I forgot to uncomment and swap out the imperative style.
This commit is contained in:
28
src/basic.rs
28
src/basic.rs
@ -52,20 +52,26 @@ pub fn longest<'a>(strings: &'a [String]) -> Option<&'a str>
|
||||
return None;
|
||||
}
|
||||
|
||||
// Imperative programming style.
|
||||
//
|
||||
// ```Rust
|
||||
// This is the current longest string. (index, length)
|
||||
// let mut longest: (usize, usize) = (0, 0);
|
||||
// for (index, string) in strings.iter().enumerate()
|
||||
// {
|
||||
// if string.len() > longest.1
|
||||
// {
|
||||
// longest = (index, string.len());
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// Some(&strings[longest.0])
|
||||
// ```
|
||||
//
|
||||
// This can also be done with functional style:
|
||||
// strings.iter().max_by_key(|s| s.len()).map(|s| s.as_str())
|
||||
let mut longest: (usize, usize) = (0, 0);
|
||||
for (index, string) in strings.iter().enumerate()
|
||||
{
|
||||
if string.len() > longest.1
|
||||
{
|
||||
longest = (index, string.len());
|
||||
}
|
||||
}
|
||||
|
||||
Some(&strings[longest.0])
|
||||
// When coding prefer the functional, declarative style.
|
||||
// It is just as fast or faster than the imperative style.
|
||||
strings.iter().max_by_key(|s| s.len()).map(|s| s.as_str())
|
||||
}
|
||||
|
||||
|
||||
|
Reference in New Issue
Block a user