aboutsummaryrefslogtreecommitdiff
path: root/lessons/src/lesson026_list_recursion
diff options
context:
space:
mode:
authorLouis Pilfold <louis@lpil.uk>2023-12-12 15:29:01 +0000
committerLouis Pilfold <louis@lpil.uk>2023-12-12 15:29:05 +0000
commitb0840f22e53f6a820b11ba538fb3a9b926fb9b29 (patch)
tree055996a034409f7e401cdd853ba5895eb93add84 /lessons/src/lesson026_list_recursion
parent819cc743eba34cdd25e25f3c6ba5891a8cb6077d (diff)
downloadtour-b0840f22e53f6a820b11ba538fb3a9b926fb9b29.tar.gz
tour-b0840f22e53f6a820b11ba538fb3a9b926fb9b29.zip
More lessons
Diffstat (limited to 'lessons/src/lesson026_list_recursion')
-rw-r--r--lessons/src/lesson026_list_recursion/code.gleam13
-rw-r--r--lessons/src/lesson026_list_recursion/text.html22
2 files changed, 35 insertions, 0 deletions
diff --git a/lessons/src/lesson026_list_recursion/code.gleam b/lessons/src/lesson026_list_recursion/code.gleam
new file mode 100644
index 0000000..370675a
--- /dev/null
+++ b/lessons/src/lesson026_list_recursion/code.gleam
@@ -0,0 +1,13 @@
+import gleam/io
+
+pub fn main() {
+ let sum = sum_list([18, 56, 35, 85, 91], 0)
+ io.debug(sum)
+}
+
+fn sum_list(list: List(Int), total: Int) -> Int {
+ case list {
+ [first, ..rest] -> sum_list(rest, total + first)
+ [] -> total
+ }
+}
diff --git a/lessons/src/lesson026_list_recursion/text.html b/lessons/src/lesson026_list_recursion/text.html
new file mode 100644
index 0000000..7f2351d
--- /dev/null
+++ b/lessons/src/lesson026_list_recursion/text.html
@@ -0,0 +1,22 @@
+<p>
+ Most commonly functions in the
+ <a href="https://hexdocs.pm/gleam_stdlib/gleam/list.html"><code>gleam/list</code></a>
+ module are used to iterate across a list, but at times you may prefer
+ to work with the list directly.
+</p>
+<p>
+ Gleam doesn't have a looping syntax, instead iteration is done through
+ recursion and pattern matching.
+</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>
+