Early preview: syntax, standard library APIs, and tooling may change.

Program StructureGenerics

Generics

Generics let one function work over many concrete types.

Type Parameters

Type parameters appear in brackets, such as [T].

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.

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.

names: List[String] = []

maybe_score: Option[Int] = None

Reusable Helpers

A small generic helper should avoid extra constraints until it needs them.

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 repeat_once[T](value: T) -> List[T]:
	[value]


func main(args: List[String]) -> Void:
	print(
		first_or(
			[1, 2, 3],
			0,
		),
	)
	print(first_or(repeat_once("ready"), "missing")) -- prints: ready

Try it

terminal
blorp run generic-helpers.brp