Code Examples

Practical examples demonstrating Kode's features.

Hello World
Basic

kode
fn main() {
    println("Hello, World!")
}

Fibonacci Sequence

kode
fn fib(n: int) -> int {
    if (n <= 1) {
        return n
    }
    return fib(n - 1) + fib(n - 2)
}

fn main() {
    for (let i = 0; i < 10; i++) {
        print(fib(i))
        print(" ")
    }
}
// Output: 0 1 1 2 3 5 8 13 21 34

Factorial Calculator

kode
fn factorial(n: int) -> int {
    if (n <= 1) {
        return 1
    }
    return n * factorial(n - 1)
}

fn main() {
    println(factorial(5))   // 120
    println(factorial(10))  // 3628800
}

Array Manipulation

kode
fn main() {
    let nums = [5, 2, 8, 1, 9]
    
    print("Original: ")
    println(nums)
    
    sort(nums)
    print("Sorted: ")
    println(nums)
    
    reverse(nums)
    print("Reversed: ")
    println(nums)
    
    println("Length: " + str(len(nums)))
}
// Output:
// Original: [5, 2, 8, 1, 9]
// Sorted: [1, 2, 5, 8, 9]
// Reversed: [9, 8, 5, 2, 1]
// Length: 5

Higher-Order Functions

kode
fn apply(f: fn, x: int) -> int {
    return f(x)
}

fn double(x: int) -> int {
    return x * 2
}

fn triple(x: int) -> int {
    return x * 3
}

fn main() {
    println(apply(double, 5))  // 10
    println(apply(triple, 5))  // 15
}

Closures Example

kode
fn makeCounter() -> fn {
    let count = 0
    return fn() {
        count = count + 1
        return count
    }
}

fn main() {
    let counter = makeCounter()
    println(counter())  // 1
    println(counter())  // 2
    println(counter())  // 3
}

Struct with Methods

kode
struct Rectangle {
    width: float,
    height: float
}

impl Rectangle {
    fn area() -> float {
        return this.width * this.height
    }
    
    fn perimeter() -> float {
        return 2 * (this.width + this.height)
    }
}

fn main() {
    let rect = Rectangle { width: 10.0, height: 5.0 }
    println("Area: " + str(rect.area()))           // 50.0
    println("Perimeter: " + str(rect.perimeter())) // 30.0
}

Pattern Matching Example

kode
enum Status {
    Success(value: int),
    Error(message: string),
    Pending
}

fn processStatus(status: Status) {
    match (status) {
        Status.Success(v) => println("Got value: " + str(v)),
        Status.Error(msg) => println("Error: " + msg),
        Status.Pending => println("Still waiting...")
    }
}

fn main() {
    processStatus(Status.Success(42))
    processStatus(Status.Error("Connection timeout"))
    processStatus(Status.Pending)
}
// Got value: 42
// Error: Connection timeout
// Still waiting...

Simple Calculator

kode
fn calculate(op: string, a: int, b: int) -> int {
    match (op) {
        "add" => return a + b,
        "sub" => return a - b,
        "mul" => return a * b,
        "div" => return a / b,
        _ => return 0
    }
}

fn main() {
    println(calculate("add", 10, 5))  // 15
    println(calculate("sub", 10, 5))  // 5
    println(calculate("mul", 10, 5))  // 50
    println(calculate("div", 10, 5))  // 2
}