gpt4 book ai didi

closures - 闭包的类型别名

转载 作者:行者123 更新时间:2023-11-29 08:05:38 26 4
gpt4 key购买 nike

我原以为下面的代码会起作用:

use std::num::{Num};
use std::fmt::{Show};

pub type GradFn<T : Num> = for<'a> fn(&'a [T]) -> (T, Vec<T>);

fn minimize<T : Show, F>(f : GradFn<T>, x0 : &[T]) {
// some no-op to test types
print!("{}",f(x0))
}

fn main() {
let xSquared : GradFn<f64> = |x : &[f64]| -> (f64, Vec<f64>) {
return (x[0] * x[0], vec![2.0 * x[0]]);
};
let (fx, grad) = xSquared(vec![2.0f64].as_slice());
print!("{}", fx);
}

但我遇到编译器错误(请参阅 here ):

<anon>:12:32: 14:4 error: mismatched types: expected `fn(&'a [f64]) -> (f64, collections::vec::Vec<f64>)`, found `|&[f64]| -> (f64, collections::vec::Vec<f64>)` (expected extern fn, found fn)
<anon>:12 let xSquared : GradFn<f64> = |x : &[f64]| -> (f64, Vec<f64>) {
<anon>:13 return (x[0] * x[0], vec![2.0 * x[0]]);
<anon>:14 };

最佳答案

fn 没有定义闭包类型;它定义了裸函数指针(即指向使用 fn 关键字定义的函数的指针)。这就是为什么不能将闭包分配给 GradFn 的原因。相反,您想使用 Fn , FnMutFnOnce .

为了编译这段代码,我还需要做一些更改:

  • 最小化 时,您编写的f 参数按值接收未调整大小的类型,这是被禁止的。您还放置了一个不使用的 F 类型参数。您可能打算约束 F 并使用 F 作为 f 的类型。
  • 编译器不允许我们在类型参数约束中使用类型别名;我们需要充分说明这个特征。这意味着类型别名基本上没有用。
  • 我删除了 xSquared 上的类型注释,这是不必要的。这让我完全删除了类型别名。

这是最终代码:

#![feature(unboxed_closures)]

use std::num::{Num};
use std::fmt::{Show};

fn minimize<T: Show, F: FnMut(&[T]) -> (T, Vec<T>)>(mut f: F, x0: &[T]) {
// some no-op to test types
print!("{}", f(x0))
}

fn main() {
let xSquared = |x: &[f64]| -> (f64, Vec<f64>) {
return (x[0] * x[0], vec![2.0 * x[0]]);
};
let (fx, grad) = xSquared(vec![2.0f64].as_slice());
print!("{}", fx);
}

关于closures - 闭包的类型别名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27597854/

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