Complete these tasks to reinforce what you learned in this module.
Write a function apply_twice(f: impl Fn(i32) -> i32, x: i32) -> i32
that returns f(f(x)) (it applies the closure to x, then applies it again to
that result). In main, define a closure double that multiplies its argument
by 2 and pass it to apply_twice with x = 5. Then capture a local variable
factor = 3, define a closure scale that multiplies its argument by factor
(capturing factor from the surrounding scope), and pass scale to
apply_twice with x = 5. Print both results in the format shown below.
apply_twice takes the closure by impl Fn(i32) -> i32, so it can be
called more than once: f(f(x)). double is |n| n * 2; scale is
|n| n * factor, which captures factor by shared reference because it only
reads it. double(double(5)) is 20; scale(scale(5)) is 3 * (3 * 5) = 45.// Task 1: pass a closure to a function taking `impl Fn`. See tasks/TASKS.md.
fn main() {
todo!("Write apply_twice(f: impl Fn(i32) -> i32, x: i32), then call it with `double` and a `scale` closure that captures `factor`");
}
Write a function run_three_times<F: FnMut() -> i32>(mut action: F)
that calls action() three times, printing tick -> N (where N is the value
returned) on each call. In main, create a mutable variable count = 0 and a
closure counter that increments count by 1 and returns the new value
(capturing count by mutable reference). Pass counter to run_three_times,
then — after the closure's borrow has ended — print the final value of count.
count, it implements FnMut, so the
function parameter must be mut action: F to call it. The closure body is
{ count += 1; count }. Passing counter into run_three_times moves it; once
the function returns, the closure (and its &mut count borrow) is gone, so you
can read count again afterward.// Task 2: a stateful FnMut counter. See tasks/TASKS.md.
fn main() {
todo!("Write run_three_times<F: FnMut() -> i32>(mut action: F), then pass a `counter` closure that captures `count` by &mut and print the final count");
}