From 032f840e212f82f9b940fe75cdd4789db9aa2ba2 Mon Sep 17 00:00:00 2001 From: Marcin Puc Date: Sun, 14 Mar 2021 20:35:28 +0100 Subject: Add {iterator, list}.last --- src/gleam/iterator.gleam | 17 +++++++++++++++++ src/gleam/list.gleam | 17 +++++++++++++++++ 2 files changed, 34 insertions(+) (limited to 'src') 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 }) +} -- cgit v1.2.3