我是闭包新手,所以我不明白为什么出现以下错误。如果我不包括第二个参数,则其工作例如:
fn obj_x(x: Vec<f64>) -> f64 {
return 0.0;
};
let f = |x: &Vec<f64>| obj_x(x.to_vec());
这是我的封信:
fn foo() {
let f = |x: &Vec<f64>, N: usize| obj_x(x.to_vec(), N);
}
fn obj_x(x: Vec<f64>, N: usize) -> f64 {
let x = (x[0] + 4.0).powf(2.0);
return x;
}
error[E0593]: closure is expected to take 1 argument, but it takes 2 arguments
--> src/main.rs:120:44
|
114 | let f = |x: &Vec<f64>, N: usize | obj_x(x.to_vec(),N);
| ------------------------- takes 2 arguments
...
120 | let mut fmin = Funcmin::new(&mut x,&f,&g,"cg");
| ^^ expected closure that takes 1 argument
|
这是我的完整代码:
fn obj_x(x: Vec<f64>, N: usize) -> f64 {
let x = (x[0] + 4.0).powf(2.0);
return x;
}
fn gradient_x(x: Vec<f64>) -> Vec<f64> {
return vec![2.0 * (x[0] + 4.0)];
}
fn test() {
let f = |x: &Vec<f64>, &N: usize| obj_x(x.to_vec(), N);
let g = |x: &Vec<f64>| gradient_x(x.to_vec());
let mut x = vec![40.0f64];
let mut N = 2220;
{
//you must create a mutable object
let mut fmin = Funcmin::new(&mut x, &f, &g, "cg");
fmin.minimize();
}
println!("{:?}", x);
}
答案 0 :(得分:0)
此解决方案对我有用:声明
ul.first
并命名为
ul.foo