Own-Programming-Language-Tu.../examples/basics/pattern_matching.own
aNNiMON cce75927b8 Change list pattern matcher behavior for single element
match [1] {
  case [x]:
}
Before: x = [1]
After: x = 1

x will be the first (and single) value of an array
2024-01-12 20:52:30 +01:00

65 lines
1.3 KiB
Scala

use "std"
use "types"
v = rand(10)
println match v {
case 0: "Zero"
case 1: "One"
case x if x <= 5: "Two..five"
case _: "Six..nine"
}
def match1(v) = match v {
case 1: "One"
case "Two": 2
case x if typeof(x) == NUMBER: "Number"
case x if typeof(x) == STRING: "String"
case _: "other"
}
println match1(1)
println match1(322)
println match1("test")
println match1("Two")
println match1([2])
println "\nRecursive factorial"
println factorial(6)
def factorial(n) = match n {
case 0: 1
case _: n * factorial(n - 1)
}
println "\nPattern matching on arrays"
println printArrayRecursive([1, 2, 3, 4, 5, 6, 7])
def printArrayRecursive(arr) = match arr {
case [head :: tail]: "[" + head + ", " + printArrayRecursive(tail) + "]"
case []: "[]"
case other: "[" + other + ", []]"
}
println "\nPattern matching on arrays by value"
def tupleMatch(x) = match x {
case (0, 0): "00"
case (1, 0): "10"
case (0, 1): "01"
case (1, 1): "11"
case (2, _): "2?"
case _: "unknown"
}
println tupleMatch([0, 1])
println tupleMatch([1, 1])
println tupleMatch([2, 1])
println tupleMatch([3, 9])
println "\nFizzBuzz with pattern matching"
for i = 1, i <= 100, i++ {
println match [i % 3 == 0, i % 5 == 0] {
case (true, false): "Fizz"
case (false, true): "Buzz"
case (true, true): "FizzBuzz"
case _: i
}
}