gpt4 book ai didi

function - 如何在 Rust 中实现多级柯里化(Currying)函数?

转载 作者:行者123 更新时间:2023-12-03 11:26:29 25 4
gpt4 key购买 nike

我尝试实现类似于 Functional Programming Jargon in Rust 的柯里化(Currying)函数:

fn add_origin(x: i32) -> impl Fn(i32) -> i32 {
return move |y| {
x + y
};
}

fn main() {
let add5 = add_origin(5);
println!("Call closure: {}", add5(6));
}
这可行,但如果我更深一层:
fn add(x: i32) -> impl Fn(i32) -> impl Fn(i32) -> i32 {
return move |y: i32| {
return move |z: i32| {
x + y + z
}
};
}

fn main() {
let add5 = add(5);
let add5_10 = add5(10);
println!("Call closure: {}", add5_10(6));
}
编译器不接受并告诉我:
error[E0562]: `impl Trait` not allowed outside of function and inherent method return types
--> src/main.rs:7:35
|
7 | fn add(x: i32) -> impl Fn(i32) -> impl Fn(i32) -> i32 {
| ^^^^^^^^^^^^^^^^^^^

error: aborting due to previous error
为什么不允许这样做? Rust 有更好的选择吗?

最佳答案

impl Trait语法只能用于函数签名的参数位置或返回位置。这两个都很好:

fn takes_fn(fn_arg: impl Fn(i32) -> i32) {}

fn returns_fn() -> impl Fn(i32) -> i32 {
|x| x
}
但是,这些都不起作用:
fn takes_fn(fn_arg: impl Fn(i32) -> impl Fn(i32) -> i32) {}

fn returns_fn() -> impl Fn(i32) -> impl Fn(i32) -> i32 {
|x| x
}
因为第二个嵌套 impl Trait不再在参数或返回位置,但现在是参数或返回类型签名的一部分,这是不允许的。基本上,多个嵌套 impl Trait s 永远不会工作,无论你把它们放在哪里,你总是会得到相同的编译错误。
好消息是这不会阻止你完成你想要完成的事情,因为 impl Trait只是语法糖,它的使用是可选的。在您的特定示例中,我们可以使用盒装特征对象来返回您的柯里化(Currying)函数。
fn add(x: i32) -> impl Fn(i32) -> Box<dyn Fn(i32) -> i32> {
move |y: i32| {
Box::new(move |z: i32| {
x + y + z
})
}
}

fn main() {
let add5 = add(5);
let add5_10 = add5(10);
println!("Call closure: {}", add5_10(6)); // prints "Call closure: 21"
}
playground
也可以看看:
  • What does `impl` mean when used as the argument type or return type of a function?
  • What makes `impl Trait` as an argument "universal" and as a return value "existential"?
  • 关于function - 如何在 Rust 中实现多级柯里化(Currying)函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64005006/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com