LearnTypesGenerics

Generics

Write one form that works with many types.

A generic form works with more than one type. It keeps the same idea and changes the item type.

let identityFn[T] (input : T) : T := input;
let identityType := forall (T : Type) -> T -> T;

identityFn[Int](8080);

A box can hold an Int or a String. The box idea stays the same. The item type changes.

Generics help remove copied code. Use them when the rule is truly the same for many types.

partial marks a definition that is not complete yet. Use it only as a clear edge while a type-level idea is still being filled in. Normal app code should prefer complete definitions.

let Vec[T, n : Nat] := data {
  | Nil() -> Vec[T, 0]
  | Cons(head : T, tail : Vec[T, n]) -> Vec[T, n + 1]
};

partial let parsePort(text : String) : Int := 0;

Use generics when one rule really works for many item types. If the rule changes by type, prefer separate names or a shape.