w3resource

Rust Higher-Order function for Tuple modification

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

Write a higher-order Rust function that takes a closure and a vector of tuples, applies the closure to each tuple element-wise, and returns a new vector of tuples.

Sample Solution:

Rust Code:

fn apply_closure_to_tuples<T, U, F>(tuples: Vec<(T, U)>, closure: F) -> Vec<(T, U)>
where
    F: Fn(T, U) -> (T, U), // Closure trait bound
{
    tuples.into_iter() // Convert the input vector into an iterator
        .map(|(t, u)| closure(t, u)) // Apply the closure to each tuple element-wise
        .collect() // Collect the modified tuples into a new vector
}

fn main() {
    let tuples = vec![(10, 'a'), (20, 'b'), (30, 'c'), (40, 'd')];
    println!("Original tuples: {:?}", tuples);
    let modified_tuples = apply_closure_to_tuples(tuples, |x, y| (x * 2, y.to_ascii_uppercase())); // Example usage: Double the first element and convert the second element to uppercase
    println!("Modified tuples: {:?}", modified_tuples);
}

Output:

Original tuples: [(10, 'a'), (20, 'b'), (30, 'c'), (40, 'd')]
Modified tuples: [(20, 'A'), (40, 'B'), (60, 'C'), (80, 'D')]

Explanation:

In the exercise above,

  • apply_closure_to_tuples Function:
    • Input: It takes a vector of tuples 'tuples' and a closure 'closure' as arguments. The closure is expected to take two arguments of types "T" and "U" and return a tuple (T, U).
    • Output: It returns a vector of tuples (T, U).
    • Functionality:
      • The function converts the input vector 'tuples' into an iterator using "into_iter()".
      • It applies the closure 'closure' to each tuple element-wise using map(|(t, u)| closure(t, u)).
      • The result is collected into a new vector using "collect()".
    • Trait Bound: The closure 'closure' is constrained to implement the Fn(T, U) -> (T, U) trait.
  • main Function:
    • It initializes a vector of tuples 'tuples'.
    • Prints the original tuples.
    • Calls "apply_closure_to_tuples()" with a closure that doubles the first element of each tuple and converts the second element to uppercase.
    • Prints the modified tuples.

Rust Code Editor:


Previous: Rust function for modifying characters with Closure.
Next: Rust function for modifying Option values.

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.