Setting
I am designing a crate which performs numerical calculations but abstracts over the underlying types in question such that it can be used with static, dynamic, Vectors, Matrices, etc. A typical function in this context may look like this:
fn calculate<X>(increments: impl IntoIterator<Item=X>) -> X
where
X: num::Zero + core::ops::AddAssign<X>,
{
increments
.into_iter()
.fold(X::zero(), |acc, x| acc+x)
}
It is obvious for me to test very frequently with types from the popular nalgebra crate.However the situation becomes problematic when dealing with dynamically sized objects which do no implement the num::Zero
trait. These objects do implement the general From
trait but this trait carries no information about whether the object is zero or not. They also implement Default
but this initializes a 0x0-dimensional matrix with no entries.
Question
So my question is: Is it reasonable and possible to generalize the existing num::Zero
trait to also include constructor methods based on external input?
Nalgebra already provides the ::zeros(nrows, ncols)
methods to construct empty matrices but they do not fall under any trait. In the future, we will probably see many more crates for abstractions of vectors, tensors (such as ndarray) etc. (possibly on the GPU as well).
Example
An initial attempt from me looked like this:
trait ZeroFrom<S> {
fn zero_from(s: &S) -> Self;
}
impl ZeroFrom<[usize; 2]> for nalgebra::DMatrix<f64> {
fn zero_from(shape: &[usize; 2]) -> Self {
nalgebra::DMatrix::zeros(shape[0], shape[1])
}
}
See this playground example.