better generics

better generics
Photo by JĂșnior Ferreira / Unsplash

It dawned on me looking at some old notes that I once had an idea for generic container using the sub-index syntax.

Instead of Array of: Person you'd write Array[Person]. I wondered - well, can't I do that in STZ right now? and do I want to?

One of the awkward pieces of syntax is when we have to write brackets around a type just to specialise in, eg:

people: (OrderedList of: Person) = database get-people.

If we implemented specialisation using [] instead of: we'd gain the ability to write it like this:

people: OrderedList[Person] = database get-people.

Right now the specialisation code is written like this:

[List of: element-class]
  [List: Class, element-class: Class -> Class |
    {...List, #element-class: element-class}].

The only change needed is this:

[List[element-class]]
  [List: Class, element-class: Class -> Class |
    {...List, #element-class: element-class}].

This is such a simple change yet cleans up the syntax so much I wondered why hadn't I done this from the start?

Any kind of message can be used to pass multiple parameters to a type to get a new specialised subtype; but of: is by and far the most common one. Where this falls flat on its face is Map which requires both a key and a value type.

But wait! doesn't comma (,) work just about anywhere there's an expression? doesn't that therefore mean the following would work:

ArrayConfiguration :: {of: Class, length: UnsignedInteger}.
[Array[configuration]]
  [Array: Class, configuration: ArrayConfiguration -> Class |
    {...Array,
     #element-class: configuration of,
     #length: configuration length}].

[Map[key-value-classes]]
  [Map: Class,
   key-value-classes: Array[{of: Class, length: 2}]
   -> Class |
    {...Map,
     #key-class: key-vaue-classes[0],
     #element-class: key-value-classes[1]}].
uuid-to-person: Map[UUID, Person] = database get-uuid-to-person.

This cleans up the usage syntax considerably. I'm very pleased with this. I also hadn't really realised I could pass through a configuration-type object as the index key too allowing the use of [] instead of () when defining a fixed length Array as well.

This is the kind of power I'd expect from objects but I'd never imagined they'd express themselves so well in a typing system such as the one in STZ.