Generics
Generics let one function work over many concrete types.
Type Parameters
Type parameters appear in brackets, such as [T].
generic.brp
pure func first_or[T](items: List[T], fallback: T) -> T:
items.get(0).get_or(fallback)Inferred Type Params
The call site usually determines generic types from arguments.
infer-generic.brp
first_or([1, 2, 3], 0)
first_or(["a"], "fallback")Generic Containers
List[T], Option[T], Result[T, E], Dict[K, V], and Set[T] are generic containers.
containers.brp
names: List[String] = []
maybe_score: Option[Int] = NoneReusable Helpers
A small generic helper should avoid extra constraints until it needs them.
helper.brp
pure func swap[A, B](pair: (A, B)) -> (B, A):
(pair.1, pair.0)Example
generic-helpers.brp
pure func first_or[T](items: List[T], fallback: T) -> T:
match items.get(0):
Some(value): value
None: fallback
pure func swap[A, B](pair: (A, B)) -> (B, A):
(pair.1, pair.0)
func main(args: List[String]) -> Void:
print(first_or([1, 2, 3], 0).to_string())
print(swap(("age", 42)).0.to_string())
Try It
terminal
blorp run generic-helpers.brp