Generic Structs
Sometimes it might be necessary to define custom types that are able to work with any other type; often acting as containers.
A great example are lists; which can work with elements of any type; and for this reason we have list( int )
, list( bs )
, etc...
But lists are built into the language; how do we define our own containers?
In the same way we define generic types!
As we know structs can have multiple constructors and the same is true for generic ones; so let's try to define a type that can hold either one or two instances of the same type:
const POneOrTwo = ( ty ) => pstruct({
One: { value: ty },
Two: { fst: ty, snd: ty }
});
pgenericStruct
returns a function (and not a class like pstruct
does) that takes as input as many TermType
s as in the definition (arguments of the function passed to `pgenericStruct')
and only then returns a class; which represents the actual struct type.
const OneOrTwoInts = POneOrTwo( int ),
const OneOrTwoBS = POneOrTwo( bs );
const OneOrTwoOneOrTwoInts = POneOrTwo( POneOrTwo( int ).type );
Each time we need to deal with something that is generic Typescript needs a little help understanding what is the type of the argument.
We can make Typescript happy by making the function that returns a struct generic in typescript;
So the correct version of the snipped above would be:
const POneOrTwo = <TyArg extends TermType>( ty: TyArg ) =>
pstruct({
One: { value: ty },
Two: { fst: ty, snd: ty }
});