Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create Haskell-like functional dependencies

Tags:

rust

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?

like image 834
yong Avatar asked Jun 15 '15 12:06

yong


1 Answers

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.

like image 147
Vladimir Matveev Avatar answered Sep 22 '22 11:09

Vladimir Matveev