Skip to content

Generics vs Templates

Andrew Johnson edited this page Jul 3, 2024 · 16 revisions

There are two similar features that LM Supports that initially may seem very similar to the end user but in implementation they are quite different.

What is an Open Type?

An open type is any type that contains a type variable such as List<a>. This is the type of a generic list that hasn't been given a concrete parameter yet. When processing open types there are two philosophically distinct approaches to dealing with open types.

Generics are Type Erasure

Languages such as Rust or Java take the generic approach to open types. Upon encountering a generic parameter, that type parameter will be weakened down to its minimal parameterized bound. To practically use generic type parameters, each type must be given constraints that specify what behavior must be provided by the parameter in order to satisfy the constraint bound.

For example List<a> might not be very useful because it will erase down to the bottom type List<?> which means we know precisely nothing about the parameter and probably can't do anything useful with it. We don't even know the size of this type.

However, by adding constraints we can specify how much information that we need about the type to use it. Now if we add more information such as List<PartialOrd> we can create a generic list for things that can be ordered. This list may now allow us to sort the elements.

Templates are Code Generation

Clone this wiki locally