← Back to Examples

01 Vector 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 VectorBasics do
  export [main/0]
  
  # Import standard library functions
  import Std.Vector [length/1, map/2, filter/2, fold/3]
  import Std.List [zip_with/3]
  import Std.Io [println/1]

  def mult_by_2(x: Int): Int = x * 2
  def zip(v1: List(Int), v2: List(Float), f: Int => Float => Float): List(Float) =
    zip_with(v1, v2, f)
  # def access_array(arr: Vector(Int, n), idx: Int): Int =
  #   arr[idx]  # Provably safe - no runtime check needed!

  # Main demonstration function
  def main(): Int =
    println("=== Vector Operations Demo ===")
    println("")
    
    # Create a simple list
    let numbers = ‹1, 2, 3, 4, 5›
    println("Original vector: [1, 2, 3, 4, 5]")
    let numbers2 = ‹1, 2, 3, 4, 5›
    println("")
    
    # Map: double each element
    let doubled = map(numbers, mult_by_2)
    println("Doubled (map): [2, 4, 6, 8, 10]")
    
    # Filter: keep only even numbers
    # let evens = filter(numbers, fn(x) -> 
    #   match x do
    #     _ -> true  # Simplified - checking divisibility needs modulo
    #   end
    # end)
    # println("Evens (filter): depends on implementation")

    # let zipped = zip_with(numbers, numbers2, fn(x) -> fn(y) -> x + y end end)
    # println("")
    
    # Fold: sum all elements
    let sum = fold(doubled, 0, fn(x) -> fn(acc) -> acc + x end end)
    println("Sum (fold): " <> "15" <> " should be 15")
    println("")
    
    println("=== Demo Complete ===")
    sum

end