Uses of quantification over values ("const generics" in Rust)

My last post drew comments on reddit about the uses of const generics in Rust. As one comment said, the inability to do so hurts worst in matrix operations; see the example in aforesaid earlier post. But i more often wish for this feature; other cases include the following:

Finite sets

It can be convenient to have values of finite sets of statically known size (often called Fin, for example in the Agda standard library). In Rust, it would be particularly useful for array indexing: impl Index<Fin<n>> for [_; n], which would never panic.

I also find it useful dealing with certain coding schemes, for example: UTF-8, where the range of certain internal parametres (for example: number of codons/bytes) is statically known. (I can define an enum with the appropriate number of variants and convert to usize, in which case the compiler correctly infers the range of the value, but i must do so for each size of finite set i need, which is a horrid kludge.)

Complete tree arity

It is fairly widely known, a complete binary tree can be efficiently stored as an array. But the formula is more general; for a tree of arity a, for an element at index k-1, its parent is at index k/a-1, and its children are at indices k⨯a , k×a+1 , … , k×a+a-1. It would be convenient to specify the arity of a heap in its type, lest one pass the wrong arity and mangle the heap.

Other examples

I'm sure many uses will be found for const generics. The following others immediately come to mind:

  • Buffer/cache size
  • B-tree arity

I've not even gone into const generics of type other than usize/ℕ.

Leave a Reply

Your email address will not be published. Required fields are marked *