aboutsummaryrefslogtreecommitdiff
path: root/src/content/chapter2_flow_control/lesson07_list_recursion/en.html
blob: 8a3a7d3cbdb37a4085bcf008a3df2f88fb127ce5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<p>
  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> 
  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.
</p>
<p>
  This code sums a list by recursing over the list and adding each int to a
  <code>total</code> argument, returning it when the end is reached.
</p>