def get_two_ends(l):
match l:
case [first, *_, last]:
return (first, last)
case [_] | []:
raise ValueError("list is too short to have two ends")
case _:
raise ValueError("not a list")
fib 0 = 1
fib 1 = 1
fib n | n >= 2
= fib (n-1) + fib (n-2)
def fib(0), do: 1
def fib(1), do: 1
def fib(n) when n >= 2, do: fib(n-1) + fib(n-2)
match [head] + tail in [0, 1, 2, 3]:
print(head, tail)
match x with
| Some x => println$ x;
| None => println "NONE";
endmatch;
// pattern matching on objects, lists, and maps
class Rect(left, top, right, bottom)
fun rect_like_to_rect(v):
match v
| Rect(_, _, _, _): v
| {"LT": [l, t], "RB": [r, b]}: Rect(l, t, r, b)
| {"TL": [t, l], "RB": [b, r]}: Rect(l, t, r, b)
rect_like_to_rect({"TL": [0, 2], "RB": [10, 5]})
// ⇒ Rect(0, 2, 10, 5)
rect_like_to_rect({"LT": [0, 2], "RB": [10, 5]})
// ⇒ Rect(2, 0, 5, 10)
// pattern matching in all binding positions
class Posn(x, y)
fun flip_all([Posn(x, y), ...]):
[Posn(y, x), ...]
flip_all([Posn(1, 2), Posn(3, 4)])
// ⇒ [Posn(2, 1), Posn(4, 3)]
flip_all([Posn(5, 6)])
// ⇒ [Posn(6, 5)]
This functionality is included in switch statements.
Languages with Pattern Matching include Python, Rust, Haskell, Elixir, Coconut, MoonBit, Felix, Egison, Rhombus, HOPE, Aardvark, NPL
Languages without Pattern Matching include progsbase, Veryl
View all concepts with or missing a hasPatternMatching measurement
Read more about Pattern Matching on the web: 1.