Home / Docs / Guides

Constraints on generics

Release v0.4.0

A type parameter of a function may carry one built-in constraint (spec/20): Eq allows == and !=, Ord also allows <, <=, > and >=, and Integer also allows x.to_int(). Arithmetic on a type parameter stays undefined. An operator the constraint does not allow is U2026, with a repair that writes the constraint; a type argument that does not satisfy it is U2025. Private functions get the least constraint their body needs; public ones write it. Kinds take no constraints.

una
module demo

pub largest[T: Ord](xs: List[T], floor: T) -> T = xs.fold(initial: floor, step: fn(best, x) -> max(best, b: x))

pub total[T: Integer](xs: List[T]) -> Int = xs.map(each: fn(x) -> x.to_int()).sum()

pub tidy(names: List[Text]) -> List[Text] = names.sort()
una
-- fails with U2026
module demo

pub same[T](a: T, b: T) -> Bool = a == b

A generic function can build a structure by comparing values. Lists built by comparisons carry T's labels at their top, so combine them with the prelude (append, fold), whose parameters take labels of any kind (ADR 0067):

una
module demo

pub insert[T: Ord](sorted: List[T], item: T) -> List[T]
=
  let ahead = sorted.filter(keep: fn(s) -> s < item)
  let behind = sorted.filter(keep: fn(s) -> not (s < item))
  behind.fold(initial: ahead.append(item: item), step: fn(acc, s) -> acc.append(item: s))

Known limits of edition 0.2, which need label polymorphism (#40):

A value chosen by comparing values of T carries that decision in its label, and a written annotation that mentions T cannot hold it: let picked: T = if a == b then p else q is U4001, and so are List[T] and a kind applied to T. Leave the annotation out. Inference keeps the decision, and each call raises its result by the type argument's label. The return type -> T is fine, and both editions apply the same rule (#354):

una
module demo

pub choose[T: Eq](a: T, b: T, p: T, q: T) -> T
=
  let picked = if a == b then p else q
  picked
una
-- edition 0.1
-- fails with U4001
module demo

pub choose[T](a: T, b: T, p: T, q: T) -> T
=
  let picked: T = if a == b then p else q
  picked