Rust function for modifying Arrays element-wise
Rust Closures and Higher-Order Functions: Exercise-15 with Solution
Write a Rust function that takes a closure and a vector of arrays, applies the closure to each array element-wise, and returns a new vector of arrays.
Sample Solution:
Rust Code:
fn apply_closure_to_arrays<T, U, F>(arrays: Vec<[T; 2]>, mut closure: F) -> Vec<[U; 2]>
where
T: Copy, // Add Copy trait bound for the elements of the input array
F: FnMut(T) -> U, // Closure trait bound
{
arrays
.into_iter() // Convert the input vector into an iterator
.map(|arr| [closure(arr[0]), closure(arr[1])]) // Apply the closure to each array element-wise
.collect() // Collect the modified arrays into a new vector
}
fn main() {
let arrays = vec![[10, 20], [30, 40], [50, 60], [70, 80]];
println!("Original arrays: {:?}", arrays);
let modified_arrays = apply_closure_to_arrays(arrays, |x| x * 2);
println!("Modified arrays: {:?}", modified_arrays);
}
Output:
Original arrays: [[10, 20], [30, 40], [50, 60], [70, 80]] Modified arrays: [[20, 40], [60, 80], [100, 120], [140, 160]]
Explanation:
In the exercise above,
- apply_closure_to_arrays function:
- The function signature indicates that it takes three generic parameters: 'T', 'U', and 'F', 'T' represents the type of elements in the input arrays, 'U' represents the type of elements in the output arrays, and 'F' represents the closure type.
- The "where" clause specifies constraints on generic types. T: Copy ensures that elements of type 'T' can be copied, allowing them to be used safely in arrays.
- Inside the function, the input vector 'arrays' is converted into an iterator using into_iter().
- The '"map()" function applies the closure to each array element-wise. The closure is applied to each element of the array, producing a new element of type 'U'. The resulting array [U; 2] is constructed with modified elements.
- Finally, "collect" is used to collect the modified arrays into a new vector, which is then returned by the function.
- main function:
- An example vector of arrays 'arrays' is created.
- The "apply_closure_to_arrays()" function is called with this vector and a closure that doubles each element.
- The original and modified arrays are printed to the console for demonstration.
Rust Code Editor:
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
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-15.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics