Chapter 4

Functions

Reusable blocks of code

Defining Functions

Use the func keyword to define functions:

func greet() {
    print("Hello, World!")
}

// Call the function
greet()  // Hello, World!

Parameters

Functions can accept parameters:

func greetPerson(name) {
    print("Hello,", name + "!")
}

greetPerson("Alice")  // Hello, Alice!
greetPerson("Bob")    // Hello, Bob!

Multiple Parameters

func add(a, b) {
    return a + b
}

func introduce(name, age, city) {
    print(name, "is", age, "years old from", city)
}

result = add(5, 3)
print(result)  // 8

introduce("Alice", 30, "Jakarta")

Return Values

Use return to return a value from a function:

func square(x) {
    return x * x
}

func max(a, b) {
    if (a > b) {
        return a
    }
    return b
}

print(square(5))     // 25
print(max(10, 20))   // 20
Note

Functions without an explicit return statement return nil.

Recursion

Functions can call themselves recursively:

// Classic factorial
func factorial(n) {
    if (n <= 1) {
        return 1
    }
    return n * factorial(n - 1)
}

print(factorial(5))  // 120

// Fibonacci sequence
func fib(n) {
    if (n <= 1) {
        return n
    }
    return fib(n - 1) + fib(n - 2)
}

for (i in Range(1, 11)) {
    print("fib(" + str(i) + ") =", fib(i))
}

Closures

Functions can capture variables from their enclosing scope:

// Counter using closure
func makeCounter() {
    count = 0
    
    func increment() {
        count = count + 1
        return count
    }
    
    return increment
}

counter = makeCounter()
print(counter())  // 1
print(counter())  // 2
print(counter())  // 3

// Multiplier factory
func makeMultiplier(factor) {
    func multiply(x) {
        return x * factor
    }
    return multiply
}

double = makeMultiplier(2)
triple = makeMultiplier(3)

print(double(5))  // 10
print(triple(5))  // 15

Higher-Order Functions

Functions can be passed as arguments:

// Apply function to each element
func forEach(arr, fn) {
    for (item in arr) {
        fn(item)
    }
}

func printSquare(x) {
    print(x * x)
}

numbers = [1, 2, 3, 4, 5]
forEach(numbers, printSquare)
// Output: 1, 4, 9, 16, 25

Built-in Functions

Nevaarize provides several built-in functions:

Function Description Example
print(...) Output to console print("Hello")
len(x) Length of string/array len([1,2,3]) → 3
type(x) Get type name type(42) → "int"
str(x) Convert to string str(42) → "42"
int(x) Convert to integer int("42") → 42
float(x) Convert to float float(42) → 42.0
Range(a, b) Generate integer range Range(0, 5)