From 20e279aefda04a297c36b97b5413a1f738308a6c Mon Sep 17 00:00:00 2001 From: Richard Feldman Date: Thu, 24 Nov 2022 05:42:45 -0500 Subject: [PATCH] Add pattern matching on lists to HTML tutorial --- www/public/tutorial/index.html | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/www/public/tutorial/index.html b/www/public/tutorial/index.html index 2ae7355b2c..37345636ca 100644 --- a/www/public/tutorial/index.html +++ b/www/public/tutorial/index.html @@ -504,6 +504,25 @@ inside a 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 ->.

+

Pattern Matching on Lists

+

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 +Results 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.

+

Booleans

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