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;
|
return None;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Imperative programming style.
|
||||||
|
//
|
||||||
|
// ```Rust
|
||||||
// This is the current longest string. (index, length)
|
// 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:
|
// This can also be done with functional style:
|
||||||
// strings.iter().max_by_key(|s| s.len()).map(|s| s.as_str())
|
// When coding prefer the functional, declarative style.
|
||||||
let mut longest: (usize, usize) = (0, 0);
|
// It is just as fast or faster than the imperative style.
|
||||||
for (index, string) in strings.iter().enumerate()
|
strings.iter().max_by_key(|s| s.len()).map(|s| s.as_str())
|
||||||
{
|
|
||||||
if string.len() > longest.1
|
|
||||||
{
|
|
||||||
longest = (index, string.len());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Some(&strings[longest.0])
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
Reference in New Issue
Block a user