Apply Closure Iteratively in Rust
Write a Rust function that takes a closure and a starting value, applies the closure iteratively, and returns the final result.
Sample Solution:
Rust Code:
fn apply_closure_iteratively<F, T>(mut closure: F, mut initial_value: T, iterations: usize) -> T
where
F: FnMut(T) -> T, // Closure trait bound
T: Copy, // Required for cloning initial value
{
for _ in 0..iterations {
initial_value = closure(initial_value); // Apply the closure to the current value
}
initial_value // Return the final result
}
fn main() {
// Example usage:
let result = apply_closure_iteratively(|x| x * 3, 1, 6);
println!("Final result: {}", result); // Output: 729 (1 * 3 * 3 * 3 * 3 * 3 * 3)
}
Output:
Final result: 729
Explanation:
In the exercise above,
- The "apply_closure_iteratively()" function takes three parameters:
- closure: A closure that takes a value of type 'T' and returns a value of the same type.
- initial_value: The starting value for the iterative process.
- iterations: The number of times the closure should be applied iteratively.
- Inside the function, a "for" loop iterates 'iterations' times.
- In each iteration, the closure is applied to the 'initial_value', and the result becomes the new 'initial_value'.
- After all iterations are completed, the final result is returned.
In the example provided in the main function, the closure |x| x * 3 triples the input value. The function "apply_closure_iteratively()" is called with an initial value of 1 and 6 iterations. The final result, 729, is printed.
Rust Code Editor:
Previous: With Rust Higher-Order Filter integers function.
Next: Rust String Transformation Function.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics