w3resource

With Rust Higher-Order Filter integers function

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

Write a Rust higher-order function that takes a closure and a vector of integers, filters the integers based on the closure predicate, and returns a new vector.

Sample Solution:

Rust Code:

fn filter_with_closure<F>(numbers: Vec<i32>, predicate: F) -> Vec<i32>
where
    F: Fn(i32) -> bool, // Define the closure trait bound
{
    numbers.into_iter() // Convert the input vector into an iterator
        .filter(|&x| predicate(x)) // Filter the elements based on the closure predicate
        .collect() // Collect the filtered elements into a new vector
}

fn main() {
    // Define a vector of integers
    let numbers = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
    println!("Original numbers: {:?}", numbers); 
    
    // Define a closure predicate to filter even numbers
    let even_predicate = |x: i32| x % 2 != 0;

    // Use the higher-order function to filter the vector based on the closure predicate
    let even_numbers = filter_with_closure(numbers, even_predicate);

    // Print the filtered vector
    println!("Filtered odd numbers: {:?}", even_numbers);
}

Output:

Original numbers: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Filtered odd numbers: [1, 3, 5, 7, 9]

Explanation:

In the exercise above,

  • fn filter_with_closure<F>(numbers: Vec<i32>, predicate: F) -> Vec<i32>
    • This declares a function named "filter_with_closure()" that takes two parameters:
      • numbers: A vector of integers to be filtered.
      • predicate: A closure that takes an integer as input and returns a boolean indicating whether the integer satisfies some condition.
    • The function returns a vector of integers (Vec<i32>).
  • Where F: Fn(i32) -> bool
    • This is a trait bound specifying that the generic type "F" must implement the Fn(i32) -> bool trait. This means that "F" must be a closure that takes an "i32" as input and returns a boolean.
  • Inside the function:
    • numbers.into_iter(): Converts the input vector "numbers" into an iterator.
    • .filter(|&x| predicate(x)): Uses the "filter()" method on the iterator to retain only those elements for which the closure "predicate" returns 'true'.
    • .collect(): Collects the filtered elements into a new vector and returns it.
  • In the main function,
    • A vector 'numbers' containing integers from 1 to 10 is defined.
    • An even predicate closure is defined using a lambda expression that returns 'true' if the number is odd.
    • The "filter_with_closure()" function is called with the 'numbers' vector and the even predicate closure to filter out odd numbers.
    • The filtered vector of odd numbers is printed.

Rust Code Editor:


Previous: Modify vector elements with Rust Closure function.
Next: Apply Closure Iteratively in Rust.

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://www.w3resource.com/rust/functional-programming/rust-closures-and-higher-order-functions-exercise-4.php