Functions
Definition
Section titled “Definition”Functions are defined using the func keyword:
// Function definitionfunc add(int a, int b) { return a + b;}Recursion
Section titled “Recursion”Tulpar supports recursive functions:
// Recursive functionfunc fibonacci(int n) { if (n <= 1) { return n; } return fibonacci(n - 1) + fibonacci(n - 2);}Calling Functions
Section titled “Calling Functions”// Function callint sum = add(5, 3);int fib = fibonacci(10);Lambdas
Section titled “Lambdas”Lambdas are anonymous functions written with the => arrow. The body can be
a single expression or a block. Store them in a variable and call them, or
pass them around as values:
// Expression bodyvar add = (int a, int b) => a + b;print(add(2, 3)); // 5
// Block bodyvar square = (int x) => { return x * x; };print(square(5)); // 25
// Immediately invokedint r = ((int a, int b) => a + b)(3, 4); // 7Closures
Section titled “Closures”A lambda (or nested function) captures variables from the scope where it is defined. The captured variables live on past the enclosing function’s return, and mutations are shared — so you can build counters, accumulators, and factories:
// Factory: each adder captures its own `n`func make_adder(int n) { return (int x) => n + x;}
var add10 = make_adder(10);var add100 = make_adder(100);print(add10(5)); // 15print(add100(5)); // 105 (independent captures)
// Mutating capture: a counterfunc make_counter() { int count = 0; return () => { count = count + 1; return count; };}
var tick = make_counter();print(tick()); // 1print(tick()); // 2print(tick()); // 3