Learn about function declarations, anonymous functions, recursion, and functional programming in Walrus
Functions are first-class values in Walrus, meaning they can be assigned to variables, passed as arguments, and returned from other functions. This guide covers all aspects of working with functions.
fn add : a, b { return a + b;}// Assign function to variablelet operation = add;// Call through variablelet result = operation(10, 5);println(result); // 15
fn is_prime : n { if n < 2 { return false; } let i = 2; while i * i <= n { if n % i == 0 { return false; } i = i + 1; } return true;}fn get_primes : max { let primes = []; for i in 2..max { if is_prime(i) { primes.push(i); } } return primes;}let primes = get_primes(50);println(primes);// [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
fn map : func, list { let result = []; for item in list { result.push(func(item)); } return result;}let numbers = [1, 2, 3, 4, 5];let doubled = map(: x { return x * 2; }, numbers);println(doubled); // [2, 4, 6, 8, 10]
fn filter : predicate, list { let result = []; for item in list { if predicate(item) { result.push(item); } } return result;}let numbers = [1, 2, 3, 4, 5, 6];let odds = filter(: x { return x % 2 == 1; }, numbers);println(odds); // [1, 3, 5]
fn reduce : func, list, initial { let acc = initial; for item in list { acc = func(acc, item); } return acc;}let numbers = [1, 2, 3, 4, 5];let product = reduce( : a, b { return a * b; }, numbers, 1);println(product); // 120
let fib_cache = {};fn fibonacci_memo : n { let key = str(n); if key in fib_cache { return fib_cache[key]; } let result = 0; if n <= 1 { result = n; } else { result = fibonacci_memo(n - 1) + fibonacci_memo(n - 2); } fib_cache[key] = result; return result;}println(fibonacci_memo(30)); // Much faster than naive recursion
// Good: separate concernsfn validate_email : email { return "@" in email and "." in email;}fn send_email : to, subject, body { if not validate_email(to) { return false; } // Send email logic... return true;}// Avoid: doing too much in one functionfn process_and_send : email, subject, body { // Validation, processing, sending all mixed together}
Use descriptive function names
Function names should clearly indicate what they do: