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

FoundationsFunctions

Functions

Functions make data flow explicit with parameter and return types.

Parameters

Parameters are named and typed inside parentheses.

pure func add(a: Int, b: Int) -> Int:
	a + b

Return Types

The return type follows ->. The last expression supplies the returned value.

pure func label(score: Int) -> String:
	"score: " + score.to_string()

Local Helpers

Use a small helper when the public function wants a simpler interface than the implementation.

pure func outer(n: Int) -> Int:
	pure func inner(x: Int) -> Int:
		x + 1
	inner(n)

Recursion

Recursive functions call themselves directly.

pure func count_down(n: Int) -> Int:
	if n == 0:
		0
	else:
		count_down(n - 1)

@tail_recursive

@tail_recursive asks the compiler to verify the recursive call is in tail position.

@tail_recursive
pure func loop(n: Int, acc: Int) -> Int:
	if n <= 0:
		acc
	else:
		loop(n - 1, acc + n)

Example

factorial.brp
func factorial(n: Int) -> Int:
	if n <= 1:
		1
	else:
		n * factorial(n - 1)


@tail_recursive
func factorial_loop(n: Int, acc: Int) -> Int:
	if n <= 1:
		acc
	else:
		factorial_loop(n - 1, n * acc)


func main(args: List[String]) -> Void:
	print(factorial(5)) -- prints: 120
	print(factorial_loop(5, 1)) -- prints: 120

Try it

terminal
blorp run factorial.brp