Rust 高阶方法?

问题描述 投票:0回答:1

如果我想在 Rust 中生成多项式函数,一种方法如下,

fn new_polynomial(vec: Vec<i32>) -> impl Fn(i32) -> i32 {
    move |x| vec.iter().fold(0, |acc, a| x * acc + a)
}

但是,由于我想定义很多高阶函数(求根、微分、积分等),所以我希望将这些函数实现为方法。我的代码如下,

trait Function {
    fn new_polynomial(vec: Vec<i32>) -> Self;
    fn eval(&self, x: i32) -> i32;
}

impl<F> Function for F
where
    F: Fn(i32) -> i32,
{
    fn new_polynomial(vec: Vec<i32>) -> Self {
        move |x| vec.iter().fold(0, |acc, a| x * acc + a)
    }

    fn eval(&self, x: i32) -> i32 {
        self(x)
    }
}

并生产以下E308,

error[E0308]: mismatched types
  --> src/main.rs:14:9
   |
9  | impl<F> Function for F
   |      - expected this type parameter
...
13 |     fn new_polynomial(vec: Vec<i32>) -> Self {
   |                                         ---- expected `F` because of return type
14 |         move |x| vec.iter().fold(0, |acc, a| x * acc + a)
   |         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected type parameter `F`, found closure
   |
   = note: expected type parameter `F`
                     found closure `{closure@src/main.rs:14:9: 14:17}`
   = help: every closure has a distinct type and so could not always match the caller-chosen type of parameter `F`

希望我没有遗漏一些明显的东西。

谢谢。

rust methods types closures higher-order-functions
1个回答
0
投票

如果您想要一种将向量转换为多项式的方法,您应该在向量上实现该特征,而不是在函数上:

trait ToPolynomial {
    fn new_polynomial(self) -> impl Fn(i32) -> i32;
}

impl ToPolynomial for Vec<i32> {
    fn new_polynomial(self) -> impl Fn(i32) -> i32 {
        move |x| self.iter().fold(0, |acc, a| x * acc + a)
    }
}

Function
特征不应包含此方法:

trait Function {
    fn eval(&self, x: i32) -> i32;
}

impl<F> Function for F
where
    F: Fn(i32) -> i32,
{
    fn eval(&self, x: i32) -> i32 {
        self(x)
    }
}

您可以像这样使用这些特征:

let polynomial = vec![1,2,3].new_polynomial();
println!("{}", polynomial.eval(2));

游乐场

© www.soinside.com 2019 - 2024. All rights reserved.