我有以下高阶函数
fn ensure_tonicty(tone_fn: &fn(&f64, &f64) -> bool) -> impl Fn(&Vec<f64>) -> bool {
return |floats: &Vec<f64>| -> bool {
let first = floats.first().unwrap();
let rest = &floats[1..];
fn f(tone_fn: &fn(&f64, &f64) -> bool, prev: &f64, xs: &[f64]) -> bool {
match xs.first() {
Some(x) => tone_fn(prev, x) && f(tone_fn, x, &xs[1..]),
None => true,
}
};
return f(tone_fn, first, rest);
};
}
我的目标是返回这个 lambda 表达式。但我不知道如何有效地使用 tone_fn
。
上面的代码会报错:
error[E0621]: explicit lifetime required in the type of `tone_fn`
--> src/lib.rs:1:56
|
1 | fn ensure_tonicty(tone_fn: &fn(&f64, &f64) -> bool) -> impl Fn(&Vec<f64>) -> bool {
| ----------------------- ^^^^^^^^^^^^^^^^^^^^^^^^^^ lifetime `'static` required
| |
| help: add explicit lifetime `'static` to the type of `tone_fn`: `&'static for<'r, 's> fn(&'r f64, &'s f64) -> bool`
如果我尝试包含一个生命周期,我不确定该如何输入
impl Fn
并包含这个生命周期。// where do I write `'a`?
fn ensure_tonicty<'a>(tone_fn: &'a fn(&f64, &f64) -> bool) -> impl Fn(&Vec<f64>) -> bool {
我可以写成宏来解决这个问题,但我想知道是否有其他方法可以不用宏来实现。
Copy
类型的引用,这肯定会让事情变得更加困难。另外需要知道的是,如果你要从另一个函数中返回闭包,那么你 必须 使用move
闭包。否则它将引用不再在作用域内的变量。 - Peter Hall