A Little About HLists
The final form of all typestate enjoyers in Rust is the obsession with the elusive heterogeneous (as opposed to homogeneous) list (hlist), but what is an hlist? What does it look like? How does it work? What can be done with it? And most important, how does it taste is it useful?
Alright, I’m interested #
Consider the following structure
enum List<T> {
Nil,
Cons(T, Box<Self>)
}
This is a linked, possible infinite, list that is recursively defined. We know all of its elements are of type T and the list must always have Nil at the end. Cons and Nil are values, but what if we lifted them up one level to types? We get hlists!
The hlist is a recursive data structure which is comprised of a head and a tail existing at the type level! It “knows” the type of each of its elements since the terms of the hlist type is a term of each type in the hlist, and it is necessarily finite since each element must be known at compile time.
Despite the hlist existing at the type level, it is still useful, as the elements of the hlist are terms that can be manipulated freely.
While the elements of a hlist do not have to be unique, it is still best for them to be unique as it allows us to do fun things with them. If they were non-unique then some of the trait implementation we will discuss in the post will fail, as we make use of Rust inferring the most suitable type for us to ‘find’ the right implementation, sometimes if there are duplicate types in our hlist then there are 2 matching implementations being inferred. Rust won’t pick an implementation for us there.
The recursive part is neat because it allows us to implement traits in an inductive manner by implementing the ‘inductive case’ and the ‘base case’, but what does an hlist actually look like?
There is one canonical form that is often displayed in one of two manners
// the names cons and nil come from Lisp
// Inductive Case
struct Cons<Head, Tail>(pub Head, pub Tail);
// Base Case
struct Nil;
or
// Inductive Case
type Cons<Head, Tail> = (Head, Tail);
// Base Case
type Nil = ();
We will make use of the latter form for the remainder of this post. Notice how Cons and Nil are now types instead of enum variants. Furthermore you may notice that there are no constraints on the generic parameters. This is standard convention in Rust, but we also haven’t introduced any thing to contrain the generics parameters with yet!
The idea is that the generic type T will either be another Cons or will be the end of the list Nil. The following are both hlists
let hlist_cons: Cons<&str, Cons<i32, Cons<String, Nil>>> = Cons("hi", Cons(-1, Cons("argh".to_owned(), Nil))):
let hlist_tup: (&str, (i32, (String, ()))) = ("hi", (-1, ("argh".to_owned(), ()))):
let empty_list: Nil = Nil; // or let empty_list: () = ();
Notice how both end with Nil or ()? Those are their respective ’empty lists’, or the ‘base case’ of our inductive structure. All hlists must end with a unit (struct).
We now add an actual constraint that we can apply when necessary
pub trait List {}
// Non-empty List
impl<Head, Tail> List for (Head, Tail) where Tail: List {}
// Empty List
impl List for ()
And now what? #
Well, my dear reader, the real fun begins! Assuming our hlist is truly heterogeneous, that being all types occurring within it are distinct. we can implement traits checking if certain types are present in the hlist! The way this works is that the trait is implemented if the type is present as a head, and not implemented if it is not. Brilliant!
As for all things inductive, we will want to start with the base case. Remember how just 2 sentences ago I stated that the trait should be implemented if the type is present as a head? That is exactly our base case!
trait Find<X> {}
impl<X, Tail> Find<X> for (X, Tail) where Tail: List {}
Simple right? Now on to the hard part, our inductive case. Naively we try something akin to
impl<X, Head, Tail> Find<X> for (Head, Tail) where Tail: Find<X>
Huh? Darn! That overlaps with our base case, which Rust does not approve of. We can’t change (H, T) as that is simply the form of our hlist, therefore the only thing we can change is the trait. A fact that should be widely known is that a trait indexed by distinct types can be implemented for the same type.
Let’s try that, amending our Find definition to
trait Find<X, N> {}
Here comes the tricky part — what is our base case? Think about it like this, suppose that at step we haven’t found X yet, then we will want to check at , but where do we keep track of the step then? Unsurprisingly it is exactly the parameter N we just added to our Find definition!
How does this relate to the parameter N exactly? Well the natural is kind of the unit struct (), and from that we can construct 1= ((), 0), 2 = ((), 1), 3 = ((), 2) or inductively n + 1 = ((), n). Hey, that’s just an hlist (for those interested, this is the same as showing the free monoid indexed by a unit type is isomorphic to the natural numbers, i.e. )
We implement
impl<X, Tail> Find<X, ()> for (X, Tail) {}
That was our base case 0. Now recall your torturous Sets & Logic course: we should assume that holds, then show . Assuming something holds is kind of like a trait bound, and showing something holds is kind of like implementing a trait… so let’s give that inductive case another shot
// This is what we want to prove
type Plus1<N> = ((), N);
impl<X, Head, Tail, N> Find<X, Plus1<N>> for (Head, Tail) where
// Our assumptions
Tail: Find<X, N>
{}
Tada! Now we know if L: Find<i32, N> for some N, then L is an hlist containing i32, but how do we find N? The neat thing is that we do not have to find N at all, Rust will infer N for us if it exists.
Observe
fn has_i32<L, N>()
where
L: Find<i32, N>
{
}
has_i32::<(i32, (i64, ())), _>();
// The following won't compile
// has_i32::<(u32, (i64, ())), _>();
Using this induction trick we can make more operations on arbitrary hlists. As an exercise, try implementing an operation which removes an element from the hlist, then multiple elements. Now see if you can check if two hlists are isomorphic. Try to write a trait that verifies that an hlist only contains distinct types!
I hate the syntax! #
You have three options: suck it up, macros, or macros. Going in order of fun, sucking it up is the least fun as typing nested hlists is annoying. Unfortunately we are not allowed to freely convert tuples and hlists of “equivalent” sizes from and to one another because they have different layouts. That leaves us with the oh-so-scary macros, in particular macro_rules! as proc-macros are too much for the feeble minded (me).
Starting with a simple macro
macro_rules! list {
($head:tt, $($tail:tt,)*) => {
($head, $crate::list!($($tail,) *))
};
() => {
()
};
}
This is why I liked the standard tuple representation of hlists: we get the pattern, type, and expression syntax all in one (shitty) macro. If you are annoying like me, you aren’t satisfied by this user facing easily misused macro. Sure we could ‘improve’ the ’ergonomics’ of our macro by ‘distinguishing’ the different ‘cases’ and adding ‘helpful’ ’errors’… or we could generate functions to convert tuples of up to size 126 (more is possible but the default recursion limit of Rust is 128) to hlists and back.
Simply define the traits
// https://codeberg.org/angusyoung/listicle/src/commit/dfddc374aaedd9d47c1e0e6af7ae79d1cd2fa5ff/src/lib.rs#L12-L23
/// Convert a [`List`] into a `[Tuple]`
pub trait ToTuple {
type Tuple;
fn to_tuple(self) -> Self::Tuple;
}
/// Convert a [`Tuple`] into a `[List]`
pub trait ToList {
type List;
fn to_list(self) -> Self::List;
}
and the macro
// https://codeberg.org/angusyoung/listicle/src/commit/dfddc374aaedd9d47c1e0e6af7ae79d1cd2fa5ff/src/lib.rs#L36-L61
macro_rules! impl_conversion {
($($l:tt,)* ) => {
impl<$($l), *> $crate::ToTuple for $crate::list!($($l,)*) {
type Tuple = ($($l,)*);
#[allow(clippy::used_underscore_binding)]
#[allow(clippy::just_underscores_and_digits)]
fn to_tuple(self) -> Self::Tuple {
let $crate::list!($($l,) *) = self;
#[allow(clippy::unused_unit)]
($($l,)*)
}
}
impl<$($l), *> $crate::ToList for ($($l,)*) {
type List = $crate::list!($($l,) *);
#[allow(clippy::used_underscore_binding)]
#[allow(clippy::just_underscores_and_digits)]
fn to_list(self) -> Self::List {
let ($($l,)*) = self;
$crate::list!($($l,) *)
}
}
};
}
Now all that is left is to invoke the macro with as many arguments as you want (subject to recursion limits which you may increase)! This can be done with a build script easily and then included in the main file. As long as this is its own separate crate there will be no slowdown issues.
Set those hlists into a theory #
A collection of objects, that are pairwise unique? That sounds like a set to me. We’ve already shown that it is possible to check if a type is present in an arbitrary hlist, which sounds like “element of” to my ears. Removing an element is possible too and removing multiple elements is possible too. The latter is equivelant to checking if for hlists and . If we can check if they’re subsets, we can check if they’re are isomorphic/equal. Maybe we could even check if they are disjoint!
Spoiler: we can do all of that, I did it. Here, watch #
Okay I’m a bit lazy so I don’t feel like writing too much about this. Here is the crate if you just want the code.
We start with making our Find trait a bit better by allowing us to remove the type after finding it and keeping the rest. Note that this trait is only implemented if we can actually find the type, later we will create a Without trait that removes a type when possible or does nothing otherwise. I’ve removed all those flimsy trait methods because they’re irrelevant to our type level shenanigans.
trait Select<X, N> {
type Remainder;
}
You will notice we added the associated type Remainder. To get the hlist without X we simply need to rebuild the list without it, simple right? Observe our base case
impl<X, Tail> Select<X, ()> for (X, Tail) {
type Remainder = Tail;
}
See how there is no X in the remainder? We’re extracting it from our hlist!
The inductive case will look familiar
impl<X, Head, Tail, N> Select<X, ((), N)> for (Head, Tail)
where
Tail: Select<X, N>,
{
type Remainder = (Head, Tail::Remainder);
}
In fact, it is exactly the same with just the addition of an associated type. It is important that we have T::Remainder as our tail as this will recurse all the way down (where applicable) to where we match on (X, _) of which we then want to exlude X from the output.
Now we want to remove more than one type at a time, something like a list of types? ….An hlist of types?!
trait SelectMany<A, N> {
type Remainder;
}
N here is our inductive parameter and A is the hlist whose types we want to remove from Self. The base case in this case is when A = () and N = 0, the implementation is then simply
impl<T> SelectMany<(), ()> for T {
type Remainder = T;
}
We don’t have anything to remove, so we don’t need to do anything. The inductive case is a lot trickier. First you should have noticed that we implemented the Select trait first for a reason. For each type we want to remove, we can Select it and remove it, which we want to do for each type in the hlist A (the parameter of SelectMany). This gives rise to 2 inductive parameters we stuff into N. The inductive parameter I which will help with the proof of Select and the inductive parameter J which helps with the proof of SelectMany.
impl<SelectHead, SelectTail, SourceHead, SourceTail, I, J>
SelectMany<(SelectHead, SelectTail), (I, J)> for (SourceHead, SourceTail)
where
(SourceHead, SourceTail): Select<SelectHead, I>,
<(SourceHead, SourceTail) as Select<SelectHead, I>>::Remainder: SelectMany<SelectTail, J>,
{
type Remainder =
<<(SourceHead, SourceTail) as Select<SelectHead, I>>::Remainder as SelectMany<
SelectTail,
J,
>>::Remainder;
}
To keep things short, all we do is for each type we want to remove, we assume that there is a proof using I and J such that we can remove SelectHead and that SelectTail can be removed, with which we prove that SelectMany<(SelectHead, SelectTail), _> holds.
Again the assumptions are that we can remove SelectHead, we can remove SelectTail, therefore we conclude that we can remove (SelectHead, SelectTail).
Phew. Send me a message if this is still not clear and I might expand on how it works. The key trick is still that Rust will infer I and J for us (we pack them up into just N though which is fine) so that it can find the right implementation to remove each type needed.
We can create some handy aliases for SelectMany that resemble common set theory set operations
trait SubsetOf<A, I> {}
impl<A, B, I> SubsetOf<B, I> for A where B: SelectMany<A, I> {}
trait SupersetOf<A, I> {}
impl<A, B, I> SupersetOf<B, I> for A where A: SelectMany<B, I> {}
trait Isomorphic<A, I> {}
impl<I, J, L1, L2> Isomorphic<L1, (I, J)> for L2
where
L1: SelectMany<L2, I>,
L2: SelectMany<L1, J>,
{
}
These should be fairly straightforward, but if this confuses you just consider the fact that we can only “select many of A from B” if all elements of A are present in B, also known as subset of. Simply reverse the direction to get superset of, then combine both to get a set equality. I’ve called it an isomorphism because hlists are not truly sets, we are merely mimicking some operations and pretending they are.
Now we have , , , and . We are missing , , and . As of writing this I haven’t though of how to do interesection, but set minus and union are pretty easy.
We start with union, it is just concatenating two hlists together which is pretty simply.
Define
trait Concat<Rhs> {
type Out;
}
The base case is when we want to concatenate an arbitrary list with an empty list, i.e.
impl<L> Concat<()> for L {
type Out = L
}
and the inductive case is when we assume we can concatenate the tail, and we prove we can add the head which looks like
impl<LH, LT, RH, RT> Concat<(RH, RT)> for (LH, LT)
where
(LH, LT): Concat<RT>,
{
type Out = (RH, <(LH, LT) as Concat<RT>>::Out);
}
Technically it’s not truly a union, because we don’t take care of duplicates. I’m not sure how to remove duplicate elements as I tried to implement a MakeUnique<N> trait to deduplicate lists by recursing on the tail and removing all instances of the head from the tail, building it up from there, but that couldn’t be inferred by Rust so I left it be. What I did manage to do is create a check for disjointness of two sets, so we can require disjointness before unioning them.
Now moving on to setminus, we want something like Select except we want it to always succeed, which means we actually have 2 base cases:
- we find our target
X, - we don’t find our target
Xand we’ve reached the end of the list.
Define
trait Without<X, I> {
type Remainder;
}
with the base cases we covered
impl<X, Tail> Without<X, ()> for (X, Tail) {
type Remainder = Tail;
}
impl<X> Without<X, !> for () {
type Remainder = ();
}
The inductive case is equally simple. Assume that we have removed everything from the tail, then we will have removed everything from the head and tail together.
impl<X, Head, Tail, I> Without<X, ((), I)> for (Head, Tail)
where
Tail: Without<X, I>,
{
type Remainder = (Head, Tail::Remainder);
fn without(self) -> Self::Remainder {
let (h, t) = self;
(h, t.without())
}
}
Now we know how to remove a single type, let’s remove many types!
pub trait WithoutMany<A, I> {
type Remainder;
}
impl<T> WithoutMany<(), ()> for T {
type Remainder = T;
}
impl<WithoutHead, WithoutTail, SourceHead, SourceTail, I, J>
WithoutMany<(WithoutHead, WithoutTail), (I, J)> for (SourceHead, SourceTail)
where
(SourceHead, SourceTail): Without<WithoutHead, I>,
<(SourceHead, SourceTail) as Without<WithoutHead, I>>::Remainder: WithoutMany<WithoutTail, J>,
{
type Remainder =
<<(SourceHead, SourceTail) as Without<WithoutHead, I>>::Remainder as WithoutMany<
WithoutTail,
J,
>>::Remainder;
}
Observant readers will notice that I am a lazy author who has a tendency to make weird contorted sentences that are hard to read this is reminiscent of the SelectMany inductive case. Even more observant readers noticed I just s/SelectMany/WithoutMany/g because it is the same implementation with the names swapped!
For disjointness we need a simple helper trait
trait Equal<A> {}
impl<A> Equal<A> for A {}
It is simply a way to prove that A = A, or in other words it is .
Using set theory we can characterise disjointness of two sets as the following requirements
This is equivelant to saying (if the implementations exist): <A as WithoutMany<B, _>>::Out: Equal<A> and <B as WithoutMany<A, _>>: Equal<B> thus we derive
trait Disjoint<A, I> {}
impl<L1, L2, I, J> Disjoint<L1, (I, J)> for L2
where
L1: WithoutMany<L2, I>,
<L1 as WithoutMany<L2, I>>::Remainder: Equal<L1>,
L2: WithoutMany<L1, J>,
<L2 as WithoutMany<L1, J>>::Remainder: Equal<L2>,
{
}
That covers pretty much all the set operations except intersection. I don’t think I could create intersection for the same reason I couldn’t create MakeUnique – duplicate types being the culprit. What we can do is constrain uniqueness of elements like
trait UniqueList<I> {}
impl UniqueList<()> for () {}
impl<Head, Tail, I, J> UniqueList<(I, J)> for (Head, Tail)
where
(Head, Tail): Select<Head, J>,
T: UniqueList<I>
{}
If you’ve followed along closely it should be fairly obvious what is happening here, but nonetheless I will explain. We iterate over the elements of the hlist, and for each head we try to find it in the list. Suppose we find exactly 1 implementation then everything is okay, more than 1 implementation and we will get a compile error (courtesy of Select), then we just have an assumption that everything holds for the tail. Standard stuff, nuff said amirite.
You stupid theorist! There is no practical application for this! Stop living in your abstract theoretical wonderland! #
Crap, did I waste all that time writing this post? No, hlists are used in the wild by crates like brood and frunk. One application is of course an ECS library, or a web framework. Maybe an in-memory type-safe database with type based queries. Hlists can help build good developer UX, by verifying that the intermediate state of builder struct that is building an hlist is valid (or just check the final state). The world is your oyster with hlists, as long as you do not lack the imagination.
Someone should make an ECS with this #
You took the words right out of my mouth. Why hasn’t anyone made a complete ECS which abuses hlists and tuple conversions to ensure that
- systems only request components that exist in the world (defined at compile time),
- systems that are parallel accessing overlapping components fails at compile time,
- systems don’t have to be boxed but can live in the type system,
- rust-analyzer and the trait solver hate you.
This kills the “systems as entities” idea which sucks just a little bit because I think it’s cool, but the main issue is that I haven’t figured out how to prove pairwise disjointness of hlists (not that I’ve tried). Maybe if we take an hlists with base case of two inner hlists being pairwise disjoint, then the inductive case showing disjointness with the “top” hlists (through an associated type) of that assumed disjointness proof? In general while we have many of the basic blocks we haven’t generalised these for finite iterations of these operations, meaning we cannot do finite unions, finite set minus, etc. yet, which is kind of a bummer.
You should make an ECS with this #
I’ve thought about it, everyone should write an ECS at least once in their life, just like how everyone should walk up to the front of a first-year calculus lecture and write down the mean value theorem then look disappointed no one comments on it at least once in their life.
The thing is, the storage part of ECS is kind of boring, in Rust we will have to type erase and ensure that when we query components we are casting the right blobs of data back into types. We don’t get to do type shenanigans there to get compile time nonsense checks of things. I suspect it is possible to use dependent type theory (read: a programming language with a dependent type system) to alleviate that “annoyance” of mine, but I haven’t tried that yet.
Final words #
My interest in hlists is what got me into type theory, encoding stronger invariants and being able to do proofs using types appealed to me, so this is sort of an homage to that. It’s kind of funny that we manage to recreate lots of set operations by using types – that’s kind of the point sometimes in type theory, recreating set theory so that type theory can serve as a different mathematical foundation while preserving all of the set theory done historically. Although, our “recreation” of set theory is not as elegant as I would like it to be…
Further Reading #
- Scala tuple docs
- frunk crate
- brood crate
- listicle crate is where I will be doing any further hlist shenanigans