w3resource

Rust Higher-Order function for logical AND

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

Write a Rust higher-order function that takes a closure and a vector of booleans, applies the closure to each boolean, and returns the logical AND of all results.

Sample Solution:

Rust Code:

fn apply_closure_to_booleans<F>(booleans: Vec<bool>, closure: F) -> bool
where
    F: Fn(bool) -> bool, // Closure trait bound
{
    booleans.into_iter() // Convert the input vector into an iterator
        .all(closure) // Apply the closure to each boolean and return true if all results are true
}

fn main() {
    let booleans = vec![false, false, true, false];
    let result = apply_closure_to_booleans(booleans, |b| b); // Example usage: Identity function
    println!("Result: {}", result); // Print the result
}

Output:

Result: false

Explanation:

In the exercise above,

  • apply_closure_to_booleans: This function takes a vector of booleans 'booleans' and a closure closure as arguments. The closure takes a "bool" and returns a "bool".
  • Inside the function, the 'booleans' vector is converted into an iterator, and the "all()" method is used to apply the closure to each boolean. The "all()" method returns 'false' if the closure returns 'false' for all elements in the iterator.
  • In the "main()" function, an example usage of "apply_closure_to_booleans()" is demonstrated. It takes a vector of booleans and applies a closure that represents the identity function (i.e., returns the input boolean as is). Finally, it prints the result.

Rust Code Editor:


Previous: Apply Closure to concatenated strings in Rust.
Next: Rust function for maximum result with Closure.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.