aboutsummaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
Diffstat (limited to 'src')
-rw-r--r--src/gleam/iterator.gleam17
-rw-r--r--src/gleam/list.gleam17
2 files changed, 34 insertions, 0 deletions
diff --git a/src/gleam/iterator.gleam b/src/gleam/iterator.gleam
index fa49b87..499cd92 100644
--- a/src/gleam/iterator.gleam
+++ b/src/gleam/iterator.gleam
@@ -946,3 +946,20 @@ pub fn reduce(
|> Ok
}
}
+
+/// Returns the last element in the given iterator.
+///
+/// Returns `Error(Nil)` if the iterator is empty.
+///
+/// ## Examples
+///
+/// > from_list([]) |> last
+/// Error(Nil)
+///
+/// > range(1, 10) |> last
+/// Ok(9)
+///
+pub fn last(iterator: Iterator(element)) -> Result(element, Nil) {
+ iterator
+ |> reduce(fn(elem, _) { elem })
+}
diff --git a/src/gleam/list.gleam b/src/gleam/list.gleam
index 9f88063..f99b729 100644
--- a/src/gleam/list.gleam
+++ b/src/gleam/list.gleam
@@ -1431,3 +1431,20 @@ pub fn scan(
) -> List(b) {
do_scan(list, initial, [], fun)
}
+
+/// Returns the last element in the given list.
+///
+/// Returns `Error(Nil)` if the list is empty.
+///
+/// ## Examples
+///
+/// > last([])
+/// Error(Nil)
+///
+/// > last([1, 2, 3, 4, 5])
+/// Ok(5)
+///
+pub fn last(list: List(a)) -> Result(a, Nil) {
+ list
+ |> reduce(fn(elem, _) { elem })
+}