Functions
Functions make data flow explicit with parameter and return types.
Parameters
Parameters are named and typed inside parentheses.
params.brp
pure func add(a: Int, b: Int) -> Int:
a + bReturn Types
The return type follows ->. The last expression supplies the returned value.
returns.brp
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.
helpers.brp
pure func outer(n: Int) -> Int:
pure func inner(x: Int) -> Int:
x + 1
inner(n)Recursion
Recursive functions call themselves directly.
recursive.brp
pure func count_down(n: Int) -> Int:
if n == 0:
0
else:
count_down(n - 1)@tailrec
@tailrec asks the compiler to verify the recursive call is in tail position.
tailrec.brp
@tailrec
pure func loop(n: Int, acc: Int) -> Int:
if n <= 0:
acc
else:
loop(n - 1, acc + n)Example
factorial.brp
pure func factorial(n: Int) -> Int:
if n <= 1:
1
else:
n * factorial(n - 1)
@tailrec
pure 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).to_string())
print(factorial_loop(5, 1).to_string())
Try It
terminal
blorp run factorial.brp