Background: I'm using the nalgebra
library and I want to create a structure that represents a multivariate normal distribution. The number and row type is uniquely determined by a square matrix type, so I want to write something like this:
#[allow(non_snake_case)]
pub struct Multivarš©<M: SquareMat<N, V>> {
Ī¼: V,
Ī£: M,
}
If I was using Haskell, I would specify a functional dependency between M
and N
and V
. What's the best way to do this in Rust?
While Haskell has two things to express such relationship between types, fundeps and associated types, Rust has only the latter. Traits in Rust can contain type members which are assigned with concrete values at the implementation site, and the compiler considers them uniquely identified by the combination of type parameters of the trait (including Self
). So you need to define SquareMat
trait like this:
trait SquareMat {
type N;
type V;
...
}
impl SquareMat for SomeStruct {
type N = Four;
type V = f64;
...
}
And then this trait can be used like this:
#[allow(non_snake_case)]
pub struct Multivarš©<M: SquareMat> {
Ī¼: M::V,
Ī£: M,
}
If you don't control SquareMat
, well, then you're out of luck - you cannot define a functional dependency at the trait usage site, only at the trait declaration site, just like in Haskell.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With