Skip to content

Polymorph

IsaacShelton edited this page Mar 21, 2022 · 1 revision

Polymorph

Polymorphs are compile-time type variables.

They are identifiers prefixed with $.

$T
$Key
$Value

In order for polymorphs to be used, they must exist within the declaration of a function, method or struct.

func sum(a $T, b $T) $T {
    return a + b
}

struct <$T> Triplet (first, second, third $T)

Polymorphs with the same name will only match against a single type. For example, the above sum function can be called as sum("Hello ", "World!"), but not as sum("Hello", 10). This is because $T would not be consistent with the arguments types of String and long.

Loose Polymorphs

Polymorphs can be injected with ~ to allow for implicit conversion of primitive types.

$~T

Polymorphs at the top level will be automatically treated as loose when not in a container.

For example, $T will be treated the same as $~T, but <$T> List will not be treated the same as <$~T> List

See Loose Polymorphs for more information

Polymorphic Prerequisites

Sometimes it's desirable for polymorphs to only match certain categories of types. This can be done using polymorphic prerequisites:

$T~__number__
$T~__primitive__
$T~__signed__
$T~__unsigned__
$T~__struct__
$T~__pod__
$T~__assign__

See polymorphic prerequisites for more information

Body Usage

Polymorphs can be used inside of function/method bodies just like concrete types:

func sumPlusSizeof(a $T, b $T) $T {
    total $T = a + b
    return total
}
Clone this wiki locally