Earlier quoted context omitted.
As others mentioned, nowadays const generics replace this technique for most problems. This technique however is still useful if you need something like `[T; A+B]` (an array whose length is the sum of two generic constants), which is not yet possible with const generics.
How do you prove to the type-checker that e.g. `append(v: [T, N], w: [T, M]) -> [T, N + M]`? Or, to make it easier, that just `append(v: [T, N], x: T]) -> [T, N + 1]`?
Doing First Grade Math in Rust's Type System
21–30 of 43 posts
Re: Doing First Grade Math in Rust's Type System
#22Can someone give an example of a useful application of this technique? Honest question, if it is just for fun that is fine with me.
Before const generics, you needed this kind of "types" to use integer values in generics, for example for fixed-length vectors/matrices/... (and const generics still have limitations). https://doc.rust-lang.org/reference/items/generics.html#cons... They came with 1.51: https://blog.rust-lang.org/2021/03/25/Rust-1.51.0.html
Re: Doing First Grade Math in Rust's Type System
#23Re: Doing First Grade Math in Rust's Type System
#24> Here, we're using the fact that x * y = x + (x - 1) * y. We recursively calculate the second term, and then add it to the first factor!
It should say
x*y = y + (x-1)*y.Re: Doing First Grade Math in Rust's Type System
#25Re: Doing First Grade Math in Rust's Type System
#26Reading this I realize that I know nothing about Rust's type system, despite using the language daily.
Re: Doing First Grade Math in Rust's Type System
#27I'm the author of the mentioned peano and typenum libraries, if anyone has any questions.
Re: Doing First Grade Math in Rust's Type System
#28Earlier quoted context omitted.
One practical use case is for dimensional analysis. A type is then a k-tuple of type-level integers where k is the number of primitive units, e.g. (kg, m, s). Then m^2 / kg would be the tuple (-1, 2, 0). Multiplying two quantities adds the tuples elementwise. For example multiplying the above type by a quantity of type kg / m / s (corresponding to (1, -1, -1)) would give (0, 1 -1), which is the correct m / s. Additio…
This doesn't work with dimensionless numbers, as they would need to have e.g. the type `(0, 0, 0)` for multiplication but `(-1, 2, 0)` or `(0, 1 -1)` for addition. Edit: I've just realised that that's actually correct ;)
Re: Doing First Grade Math in Rust's Type System
#29Nice write-up. I'm the author of the mentioned peano and typenum libraries, if anyone has any questions.
Re: Doing First Grade Math in Rust's Type System
#30Can someone give an example of a useful application of this technique? Honest question, if it is just for fun that is fine with me.
We wrote a blog post about the Rust type-level programming part of the approach: https://blog.auxon.io/2019/10/25/type-level-registers/