Mercerenies / tfactor

0 stars 0 forks source link

Data Declarations #4

Closed Mercerenies closed 4 years ago

Mercerenies commented 4 years ago

We have record types. We need sum types. Or, more precisely, sum of product types, as that seems to be the most useful abstraction, used by many other functional languages.

As with records, I expect we'll get a module "for free" which represents the type and which can be used to store helper functions for the type.

The names of the various constructors may be defined inside the type module, or they may be defined at the same level as the type itself. I'm not certain yet.

Also, a data declaration should generate a "master" fold function, which takes N function arguments and a data argument (where N is the number of terms in the sum) and applies exactly one of the functions, depending on the shape of the data. Other, more specific pattern matching can be written in terms of this and possibly some helper macros.

Mercerenies commented 4 years ago

Closed as of 32ffa23.

The syntax is heavily inspired by OCaml and supplies pretty much traditional (parameterized) sum of product types. You do not get a free module out of it; the type dumps its constructors and fold function into the current scope, so it's recommended that for more complicated types you declare a module and define your type as t within the module.

Example syntax:

type List { 'a }
  | Nil of ( )
  | Cons of ( List { 'a } 'a )

# + Defined constructors are Nil and Cons
# + Defined fold function is *List

Alternatively, you may use GADT syntax to get the same effect.

type List { 'a }
  | Nil ( -- List { 'a } )
  | Cons ( List { 'a } 'a -- List { 'a } )

Currently, the language does not support actual existentials or GADTs, merely the syntax that resembles them (as it can be cleaner in some situations). The two are interchangeable.

Note that the name of the fold function is not currently customizable. This will become less egregious once #2 is implemented, but we will want to make it customizable nonetheless.