aboutsummaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
authorMarcin Puc <marcin.e.puc@gmail.com>2021-03-14 20:35:28 +0100
committerLouis Pilfold <louis@lpil.uk>2021-04-15 23:03:51 +0100
commit032f840e212f82f9b940fe75cdd4789db9aa2ba2 (patch)
tree3ab4789478a87881e7d5ca2424f4b06e38d2a9bd /src
parent53471ea469a5ce92a500194405a121237de5d131 (diff)
downloadgleam_stdlib-032f840e212f82f9b940fe75cdd4789db9aa2ba2.tar.gz
gleam_stdlib-032f840e212f82f9b940fe75cdd4789db9aa2ba2.zip
Add {iterator, list}.last
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 })
+}