I'm a bit confused about your intent with the Diff
trait:
pub trait Diff<T: FromPrimitive + Num> {
fn numder(z: T, f: &Fn(T) -> T, i: i8) -> T {
let h = T::from_f64(1e-10).unwrap();
(f(z + h) - f(z)) / h
}
}
Since to be used, a trait has to be implemented for a certain type, there should be something about the trait that ties it to the particular type. Either the functions defined by the trait should use Self
or self
somewhere or there should be functions that have no default implementation. If neither of those are true, you might as well just use a generic function like
fn numder<T: FromPrimitive + Num>(z: T, f: &Fn(T) -> T, i: i8) -> T {
let h = T::from_f64(1e-10).unwrap();
(f(z + h) - f(z)) / h
}
If you want to use a trait, instead of adding a generic type parameter, reference the Self
type:
pub trait Diff where Self: FromPrimitive + Num + Copy {
fn numder(self, f: &Fn(Self) -> Self, i: i8) -> Self {
let h = Self::from_f64(1e-10).unwrap();
(f(self + h) - f(self)) / h
}
}
Additionally, to get things to build, I added a trait bound for Copy
. Alternatively, you could make numder
take a &self
parameter, but then you'd need to make sure std::ops::Add
is implemented for &Self
. For now, let's keep it simple and only deal with Copy
types.
With that definition of the Diff
trait, we can implement it for Complex<T>
and f64
:
impl<T> Diff for Complex<T> where T: Copy + nt::Num + FromPrimitive {}
impl Diff for f64 {}
Though Vec<T>
won't be so simple. You'll probably want to use different traits for numbers and collections of numbers.
There are some other issues with the code that I think will make sense when you see the compilation errors, but hopefully this is enough to help get you un-stuck.