# Demo 3: Functions and Control Flow
# Function definitions, lambdas, conditionals, loops

# Function definitions
fn greet(name) {
    "Hello, " + name + "!"
}

fn add(a, b) {
    a + b
}

fn factorial(n) {
    if n <= 1 {
        1
    } else {
        n * factorial(n - 1)
    }
}

# Function calls
greet("World")
add(5, 3)
factorial(5)

# Lambdas and higher-order functions
let square = x => x * x
square(4)

let numbers = [1, 2, 3, 4, 5]
let squares = numbers.map(x => x * x)
squares

let even_numbers = numbers.filter(x => x % 2 == 0)
even_numbers

# Conditional expressions
let x = 10
if x > 5 {
    "x is greater than 5"
} else {
    "x is not greater than 5"
}

# Pattern matching
let result = match x {
    1 => "one",
    2 => "two", 
    n if n > 10 => "big number",
    _ => "other"
}
result

# Match with destructuring
let point = (5, 3)
let description = match point {
    (0, 0) => "origin",
    (x, 0) => "on x-axis",
    (0, y) => "on y-axis", 
    (x, y) if x == y => "diagonal",
    _ => "general point"
}
description

# Loops
let mut i = 0
while i < 3 {
    println("Count: " + i.to_string())
    i = i + 1
}

for num in [1, 2, 3] {
    println("Number: " + num.to_string())
}

# Range iteration
for i in 1..4 {
    println("Range: " + i.to_string())
}

# Loop with break/continue concepts (via early return)
let find_first_even = |nums| => {
    for n in nums {
        if n % 2 == 0 {
            return n
        }
    }
    null
}

find_first_even([1, 3, 4, 7, 8])