From 20e279aefda04a297c36b97b5413a1f738308a6c Mon Sep 17 00:00:00 2001
From: Richard Feldman when
, we would write Custom r g b -
Custom description -> description
branch, Custom description
would be a pattern. In programming, using
patterns in branching conditionals like when
is known as pattern matching. You may hear people say things like "let's pattern match on Custom
here" as a way to
suggest making a when
branch that begins with something like Custom description ->
.
You can also pattern match on lists, like so:
+when myList is + [] -> 0 # the list is empty + [Foo, ..] -> 1 # it starts with a Foo tag + [_, ..] -> 2 # it contains at least one element, which we ignore + [Foo, Bar, ..] -> 3 # it starts with a Foo tag followed by a Bar tag + [Foo, Bar, Baz] -> 4 # it has exactly 3 elements: Foo, Bar, and Baz + [Foo, a, ..] -> 5 # its first element is Foo, and its second we name `a` + [Ok a, ..] -> 6 # it starts with an Ok containing a payload named `a` + [.., Foo] -> 7 # it ends with a Foo tag + [A, B, .., C, D] -> 8 # it has certain elements at the beginning and end + +This can be both more concise and more efficient (at runtime) than calling List.get
+multiple times, since each call to get
requires a separate conditional to handle the different
+Result
s they return.
+Note: Each list pattern can only have one
+..
, which is known as the "rest pattern" because it's where the rest of the list goes.
In many programming languages, true
and false
are special language keywords that refer to
the two boolean values. In Roc, booleans do not get special keywords; instead, they are exposed