From b0840f22e53f6a820b11ba538fb3a9b926fb9b29 Mon Sep 17 00:00:00 2001 From: Louis Pilfold Date: Tue, 12 Dec 2023 15:29:01 +0000 Subject: More lessons --- lessons/src/lesson026_list_recursion/code.gleam | 13 +++++++++++++ lessons/src/lesson026_list_recursion/text.html | 22 ++++++++++++++++++++++ 2 files changed, 35 insertions(+) create mode 100644 lessons/src/lesson026_list_recursion/code.gleam create mode 100644 lessons/src/lesson026_list_recursion/text.html (limited to 'lessons/src/lesson026_list_recursion') 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 @@ +

+ Most commonly functions in the + gleam/list + module are used to iterate across a list, but at times you may prefer + to work with the list directly. +

+

+ Gleam doesn't have a looping syntax, instead iteration is done through + recursion and pattern matching. +

+

+ The [first, ..rest] pattern matches on a list with at least one + element, assigning the first element to the variable first and + the rest of the list to the variable rest. + By using this pattern and a pattern for the empty list [] a + function can run code on each element of a list until the end is reached. +

+

+ This code sums a list by recursing over the list and adding each int to a + total argument, returning it when the end is reached. +

+ -- cgit v1.2.3