w3resource

Rust function for maximum result with Closure

Rust Closures and Higher-Order Functions: Exercise-11 with Solution

Write a Rust function that takes a closure and a vector of floats, applies the closure to each float, and returns the maximum result.

Sample Solution:

Rust Code:

fn apply_closure_to_floats<F>(floats: Vec<f64>, closure: F) -> Option<f64>
where
    F: Fn(f64) -> f64, // Closure trait bound
{
    floats.into_iter() // Convert the input vector into an iterator
        .map(closure) // Apply the closure to each float
        .fold(None, |max, x| Some(max.unwrap_or(x).max(x))) // Find the maximum result
}

fn main() {
    let floats = vec![10.2, 12.4, 14.9, 14.31];
    let result = apply_closure_to_floats(floats, |x| x * 2.0); // Example usage: Multiply each float by 2
    match result {
        Some(max) => println!("Maximum result: {}", max), // Print the maximum result
        None => println!("Vector is empty"), // Handle the case when the vector is empty
    }
}

Output:

Maximum result: 29.8

Explanation:

In the exercise above,

  • apply_closure_to_floats: This function takes a vector of floats 'floats' and a closure 'closure' as arguments. The closure takes a 'f64' and returns a 'f64'.
  • Inside the function, the 'floats' vector is converted into an iterator. The "map()" method is used to apply the closure to each float, transforming each element.
  • The "fold()" method is then used to find the maximum result among the transformed elements. It initializes with "None" as the initial accumulator value and compares each transformed element with the current maximum (max), updating 'max' if the current element is greater.
  • In the "main()" function, an example usage of "apply_closure_to_floats()" is demonstrated. It takes a vector of floats and applies a closure that multiplies each float by 2.0. Finally, it prints the maximum result.

Rust Code Editor:


Previous: Rust Higher-Order function for logical AND.
Next: Rust function for modifying characters with Closure.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/rust/functional-programming/rust-closures-and-higher-order-functions-exercise-11.php