我一直试图以一种非常通用的方式编写一些Rust代码,但没有明确指定类型.然而,我到达了一个点,我需要将usize
转换为f64
,但这不起作用.据推测,f64
的精度不足以容纳任意的usize
值.在夜间频道上编译时,我收到一条错误消息:error: the trait `core::convert::From<usize>` is not implemented for the type `f64` [E0277]
.
那么,如果我想写尽可能通用的代码,还有什么 Select 呢?很明显,我应该使用一种可能失败的trait (不同于Into
或From
).已经有这样的事了吗?有没有一个特点可以实现as
的转换?
下面是代码.
#![feature(zero_one)]
use std::num::{Zero, One};
use std::ops::{Add, Mul, Div, Neg};
use std::convert::{From, Into};
/// Computes the reciprocal of a polynomial or of a truncation of a
/// series.
///
/// If the input is of length `n`, then this performs `n^2`
/// multiplications. Therefore the complexity is `n^2` when the type
/// of the entries is bounded, but it can be larger if the type is
/// unbounded, as for BigInt's.
///
fn series_reciprocal<T>(a: &Vec<T>) -> Vec<T>
where T: Zero + One + Add<Output=T> + Mul<Output=T> +
Div<Output=T> + Neg<Output=T> + Copy {
let mut res: Vec<T> = vec![T::zero(); a.len()];
res[0] = T::one() / a[0];
for i in 1..a.len() {
res[i] = a.iter()
.skip(1)
.zip(res.iter())
.map(|(&a, &b)| a * b)
.fold(T::zero(), |a, b| a + b) / (-a[0]);
}
res
}
/// This computes the ratios `B_n/n!` for a range of values of `n`
/// where `B_n` are the Bernoulli numbers. We use the formula
///
/// z/(e^z - 1) = \sum_{k=1}^\infty \frac {B_k}{k!} z^k.
///
/// To find the ratios we truncate the series
///
/// (e^z-1)/z = 1 + 1/(2!) z + 1/(3!) z^2 + ...
///
/// to the desired length and then compute the inverse.
///
fn bernoulli_over_factorial<T, U>(n: U) -> Vec<T>
where
U: Into<usize> + Copy,
T: Zero + One + Add<Output=T> + Mul<Output=T> +
Add<Output=T> + Div<Output=T> + Neg<Output=T> +
Copy + From<usize> {
let mut ans: Vec<T> = vec![T::zero(); n.into()];
ans[0] = T::one();
for k in 1..n.into() {
ans[k] = ans[k - 1] / (k + 1).into();
}
series_reciprocal(&ans)
}
fn main() {
let v = vec![1.0f32, 1.0f32];
let inv = series_reciprocal(&v);
println!("v = {:?}", v);
println!("v^-1 = {:?}", inv);
let bf = bernoulli_over_factorial::<f64,i8>(30i8);
}