How do I implement an `apply_n_times` function?

Kev*_*ier 2 closures rust

How do I implement an apply_n_times function which gets a function f: T -> T and a number n and the result will be a function which applies f ntimes?

E.g. apply_n_times(f, 0) equals |x| x and apply_n_times(f, 3) equals |x| f(f(f(x))).

There is no deeper sense in this function, I just want to implement it for learning reasons.

My current code:

fn apply_n_times<T>(f: Fn(T) -> T, n: i32) -> dyn Fn(T) -> T {
    if n < 0 {
        panic!("Cannot apply less than 0 times!");
    }

    if n == 1 {
        |x: T| x
    } else {
        |x| f(apply_n_times(f, n - 1)(x))
    }
}

fn times_two(n: i32) -> i32 {
    return n * 2;
}

fn main() {
    println!("{}", apply_n_times(times_two, 0)(3));
    println!("{}", apply_n_times(times_two, 1)(3));
    println!("{}", apply_n_times(times_two, 3)(3));
}
Run Code Online (Sandbox Code Playgroud)

I'm at chapter 13 of the Rust book, but I searched forward a bit. I probably have to return a Box, but I'm not really sure. I tried it and I failed.

I also wanted to change the signature to this, but this only results in problems:

fn apply_n_times<F, T>(f: F, n: i32) -> F
where
    F: Fn(T) -> T,
Run Code Online (Sandbox Code Playgroud)

Unfortunately, the compiler errors do not help me; they say what's wrong at a low level, but I was running in a circle.

She*_*ter 10

fn apply_n_times<T>(f: impl Fn(T) -> T, n: usize) -> impl Fn(T) -> T {
    move |arg| (0..n).fold(arg, |a, _| f(a))
}
Run Code Online (Sandbox Code Playgroud)

使用 ausize避免了否定检查的需要。考虑使用FnMut而不是Fn因为它对函数的用户更灵活。

也可以看看: