Functions
Functions
Basic Function Declaration
Functions are declared with the func keyword, followed by the name, parameters in parentheses, return type after ->, and a : to open the body:
func add(a: i32, b: i32) -> i32: return a + b
func greet(name: String) -> String: return "Hello " + name
func main() -> i32: let result = add(10, 32) print(result) # Output: 42
let msg = greet("Thagore") print(msg) # Output: Hello Thagore return 0Function Syntax
func <name>(<param1>: <type1>, <param2>: <type2>, ...) -> <return_type>: <body>Rules
- Parameters must have explicit type annotations:
name: Type - Return type is specified after
->and before: returnstatement is required to return a value- Indentation defines the function body
Entry Point: main
func main() -> i32 is the standard entry point for Thagore programs:
func main() -> i32: print("Program started") return 0 # 0 = successMultiple Functions
Functions can call each other:
func square(n: i32) -> i32: return n * n
func sum_of_squares(a: i32, b: i32) -> i32: return square(a) + square(b)
func main() -> i32: let result = sum_of_squares(3, 4) print(result) # Output: 25 return 0Recursive Functions
Thagore supports recursion natively:
func fib(n: i32) -> i32: if (n < 2): return n return fib(n - 1) + fib(n - 2)
func main() -> i32: let result = fib(35) print(result) # Output: 9227465 return 0Functions with String Parameters
func make_greeting(first: String, last: String) -> String: return "Hello, " + first + " " + last + "!"
func main() -> i32: let greeting = make_greeting("John", "Doe") print(greeting) return 0Functions with Float Parameters
func calc_circle(radius: f32) -> f32: let pi = 3.14159 return 2.0 * pi * radius
func main() -> i32: let circumference = calc_circle(5.0) print(circumference) return 0Functions with Default Parameters
Some standard library functions support default parameters:
# In the standard library (lib/io.tg):# func input_prompt(prompt: String = "") -> String:# ...
import io
func main() -> i32: let name = io.input_prompt("Enter your name: ") print("Hello, " + name) return 0extern func — Foreign Function Declarations
Use extern func to declare external C functions (see FFI & Import for details):
extern func sqrtf(x: f32) -> f32extern func pow(base: f64, exp: f64) -> f64
func main() -> i32: let h = sqrtf(9.0 + 16.0) print(h) # Output: 5.0 return 0