简体   繁体   English

支持可能生命周期的高阶函数

[英]Higher order functions supporting possible lifetimes

Suppose I have a higher order function, such as composition from this answer :假设我有一个更高阶的 function,比如这个答案的组成

fn compose<A, B, C, G, F>(f: F, g: G) -> impl Fn(A) -> C
where
    F: Fn(A) -> B,
    G: Fn(B) -> C,
{
    move |x| g(f(x))
}

and I want to partially apply it, as in我想部分应用它,如

fn id<T>(x: &T) -> &T { x }

fn compose_with_id<T, U, F>(f: F) -> impl Fn(&T) -> U
where
    F: Fn(&T) -> U
{
    compose(id, f)
}

This doesn't compile.这不编译。 IIUC the issue is that at the compose callsite, we must substitute a specific type for A (including a specific lifetime), but the return value needs to implement Fn(&'a T) -> U for all 'a . IIUC 的问题是,在compose调用站点,我们必须用特定类型替换A (包括特定生命周期),但返回值需要为所有'a实现Fn(&'a T) -> U I tried moving the call to compose into a closure:我尝试将调用compose到一个闭包中:

fn compose_with_id<T, U, F>(f: F) -> impl Fn(&T) -> U
where
    F: Fn(&T) -> U
{
    move |t| compose(id, f)(t)
}

This also doesn't compile.这也无法编译。 The problem is now that compose is trying to take ownership of f each time the resulting function is called.现在的问题是,每次调用生成的 function 时, compose都试图取得f的所有权。 I don't see a way to fix compose_with_id (without insisting F: Copy );我看不到修复compose_with_id的方法(不坚持F: Copy ); compose takes ownership of f , which can only happen once, so we must choose one lifetime, but the return value needs to handle any lifetime. compose拥有f的所有权,它只能发生一次,所以我们必须选择一个生命周期,但返回值需要处理任何生命周期。

We could create a variant of compose that works for references:我们可以创建一个适用于引用的compose变体:

fn compose<A, B, C, G, F>(f: F, g: G) -> impl Fn(&A) -> C
where
    F: Fn(&A) -> &B,
    G: Fn(&B) -> C,
{
    move |x| g(f(x))
}

(whose return value has a HRTB) but it can't be used for non-reference inputs. (其返回值具有 HRTB)但不能用于非参考输入。

How can I define compose such that it can be partially applied to non-copyable functions with or without reference inputs?如何定义compose以便它可以部分应用于具有或不具有参考输入的不可复制函数?

How about add lifetime annotations to compose_with_id?将生命周期注释添加到 compose_with_id 怎么样?

fn compose_with_id<'a, T, U, F>(f: F) -> impl Fn(&'a T) -> U
where
    T: 'a,
    U: 'a,
    F: Fn(&'a T) -> U,
{
    compose(id, f)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM