← Back to Examples

01 List Basics

Demonstrates fundamental list processing with map, filter, and fold

Source Code

# Example 1: Basic List Operations
# Demonstrates fundamental list processing with map, filter, and fold

module ListBasics do
  export [main/0]
  
  # Import standard library functions
  import Std.List [map/2, filter/2, fold/3]
  import Std.Io [println/1]
  
  # Main demonstration function
  def main(): Int =
    println("=== List Operations Demo ===")
    println("")
    
    # Create a simple list
    let numbers = [1, 2, 3, 4, 5]
    println("Original list: [1, 2, 3, 4, 5]")
    println("")
    
    # Map: double each element
    let doubled = map(numbers, fn(x) -> x * 2 end)
    println("Doubled (map): [2, 4, 6, 8, 10]")
    
    # Filter: keep only even numbers
    let evens = filter(numbers, fn(x) -> 
      match x do
        _ -> false  # Simplified - checking divisibility needs modulo
      end
    end)
    println("Evens (filter): depends on implementation")
    
    # Fold: sum all elements
    let sum = fold(numbers, 0, fn(x) -> fn(acc) -> acc + x end end)
    println("Sum (fold): " <> "15" <> " should be 15")
    println("")
    
    println("=== Demo Complete ===")
    sum
    # safe_divide(sum, 2)

  def double_list(numbers: List(Int)): List(Int) =
    map(numbers, fn(x) -> x * 2 end)

  def calculate(): Int =
    42

  # type NonZeroInt = Int when n != 0
  # def safe_divide(a: Int, b: NonZeroInt): Int = a / b

end