Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add [head, ..tail] patter to List patterns page #129

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ pub fn main() {
[] -> "Empty list"
[1] -> "List of just 1"
[4, ..] -> "List starting with 4"
[3, ..rest] -> "Starts with a 3, captures the rest"
[_, _] -> "List of 2 elements"
_ -> "Some other list"
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,5 +11,8 @@
The spread pattern <code>..</code> can be used to match the rest of the list.
The pattern <code>[1, ..]</code> matches any list that starts with
<code>1</code>. The pattern <code>[_, _, ..]</code> matches any list that has
at least two elements.
at least two elements. By adding a variable name after the <code>..</code>, you
can capture the remaining elements of the list. The pattern <code>[_, ..rest]</code>
will match a list with at least one element and assign the rest of the elements
to the variable <code>rest</code>.
</p>
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,14 @@
While it is more common to use functions in the
<a href="https://hexdocs.pm/gleam_stdlib/gleam/list.html" target="_blank">
<code>gleam/list</code>
</a>
</a>
module to iterate across a list, at times you may prefer to work
with the list directly.
</p>
<p>
The <code>[first, ..rest]</code> pattern matches on a list with at least one
element, assigning the first element to the variable <code>first</code> and
the rest of the list to the variable <code>rest</code>. By using this pattern
and a pattern for the empty list <code>[]</code> a function can run code on
each element of a list until the end is reached.
By using the <code>[first, ..rest]</code> pattern and a pattern for the empty
list <code>[]</code> a function can run code on each element of a list until
the end is reached.
</p>
<p>
This code sums a list by recursing over the list and adding each int to a
Expand Down