Demonstrates defining and using a custom option-like type
# Example 3: Custom Option Type
# Demonstrates defining and using a custom option-like type
module OptionType do
export [main/0]
# Import standard library
import Std.Io [println/1]
# Define our own simple option type
type MyOption(T) = Found(T) | NotFound
# Helper: find first element greater than threshold
def find_first_above(threshold: Int): MyOption(Int) =
match threshold < 10 do
true -> Found(15)
false -> NotFound
end
# Helper: safe list head using MyOption
def safe_first(list: List(Int)): MyOption(Int) =
match list do
[] -> NotFound
[h | _] -> Found(h)
end
# Main demonstration
def main(): Int =
println("=== Custom Option Type Demo ===")
println("")
# Test 1: Found value
println("Test 1: Find value above 5")
let result1 = find_first_above(5)
match result1 do
Found(v1) -> println("Found: 15")
_ -> println("Not found")
end
println("")
# Test 2: NotFound value
println("Test 2: Find value above 20")
let result2 = find_first_above(20)
match result2 do
Found(v2) -> println("Found value")
_ -> println("Not found")
end
println("")
# Test 3: Safe list access with non-empty list
println("Test 3: First element of [42, 43, 44]")
let numbers = [42, 43, 44]
let result3 = safe_first(numbers)
match result3 do
Found(v3) -> println("First element: 42")
_ -> println("Empty list")
end
println("")
# Test 4: Safe list access with empty list
println("Test 4: First element of empty list")
let empty_list = []
let result4 = safe_first(empty_list)
match result4 do
Found(v4) -> println("First element found")
_ -> println("Empty list - no first element")
end
println("")
println("=== Demo Complete ===")
0
end