aboutsummaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
authorlrosa007 <lrosa008@gmail.com>2020-11-02 18:06:24 -0500
committerLouis Pilfold <louis@lpil.uk>2020-11-03 14:02:42 +0000
commit5c4a9750a27876f648b85d9bd7ba4f0e18b66990 (patch)
treee364bb1ff5e1c661211645f2cc2a3aaa57b1503d /src
parente1dce822e1ff14664a30b429b5e2e2cbf3748221 (diff)
downloadgleam_stdlib-5c4a9750a27876f648b85d9bd7ba4f0e18b66990.tar.gz
gleam_stdlib-5c4a9750a27876f648b85d9bd7ba4f0e18b66990.zip
feat(iterator): add find function
Diffstat (limited to 'src')
-rw-r--r--src/gleam/iterator.gleam31
1 files changed, 31 insertions, 0 deletions
diff --git a/src/gleam/iterator.gleam b/src/gleam/iterator.gleam
index e75b0a7..81ef2ce 100644
--- a/src/gleam/iterator.gleam
+++ b/src/gleam/iterator.gleam
@@ -463,3 +463,34 @@ pub fn range(from start: Int, to stop: Int) -> Iterator(Int) {
|> do_range(start, stop, _)
|> Iterator
}
+
+/// Find the first element in a given iterator for which the given function returns
+/// True.
+///
+/// Returns `Error(Nil)` if the function does not return True for any of the
+/// elements.
+///
+/// ## Examples
+///
+/// > find(from_list([1, 2, 3]), fn(x) { x > 2 })
+/// Ok(3)
+///
+/// > find(from_list([1, 2, 3]), fn(x) { x > 4 })
+/// Error(Nil)
+///
+/// > find(from_list([]), fn(x) { True })
+/// Error(Nil)
+///
+pub fn find(
+ in haystack: Iterator(a),
+ one_that is_desired: fn(a) -> Bool,
+) -> Result(a, Nil) {
+ case haystack.continuation() {
+ Continue(element, continuation) ->
+ case is_desired(element) {
+ True -> Ok(element)
+ False -> find(Iterator(continuation), is_desired)
+ }
+ Stop -> Error(Nil)
+ }
+}