Function Declaration
Basic Syntax
func function_name(param1: type1, param2: type2) -> return_type {
// function body
return value
}
Simple Function
func greet(name: str) -> string {
return "Hello, " + name
}
var result @ str = greet("Alice")
display result
Parameters
Multiple Parameters
func add(a: int, b: int) -> int {
return a + b
}
var sum @ int = add(10, 20)
No Parameters
func get_pi() -> float {
return 3.14159
}
No Return Value
func print_message(msg: str) {
display msg
}
Return Values
Explicit Return
func square(x: int) -> int {
return x * x
}
Implicit Return (Last Expression)
func double(x: int) -> int {
x * 2 // Implicit return
}
Recursion
Factorial Example
func factorial(n: int) -> int {
if n <= 1 {
return 1
}
return n * factorial(n - 1)
}
display factorial(5) // Output: 120
Fibonacci
func fib(n: int) -> int {
if n <= 1 { return n }
return fib(n-1) + fib(n-2)
}
Scoping
Functions have their own scope. Variables are local to the function:
func compute() -> int {
var local @ int = 42
return local
}
display compute() // Works
// display local // Error: local not in scope
Common Patterns
Finding Maximum of Two Numbers
func max(a: int, b: int) -> int {
if a > b { return a }
return b
}
Array Sum
func sum_array(arr: [int]) -> int {
var sum @ int = 0
for i from 0~(3) {
sum = sum + arr[i]
}
return sum
}
Native User Input
Use built-in input() directly without importing any module:
var name @ str = input("Enter your name: ")
display "Hello, " + name
One-Line Conditional Expressions
Use expression-style conditionals to compute values inline:
var n @ int = 7
var label @ str = n > 5 ? "big" : "small"
var parity @ str = if n % 2 == 0 { "even" } else { "odd" }
Best Practices
- Use descriptive names: Function names should describe what they do
- Keep functions small: Each function should do one thing
- Add comments: Document complex logic
- Handle edge cases: Check for empty arrays, null values, etc.
- Use type annotations: Always specify parameter and return types