aboutsummaryrefslogtreecommitdiff
path: root/src/list.gleam
diff options
context:
space:
mode:
Diffstat (limited to 'src/list.gleam')
-rw-r--r--src/list.gleam35
1 files changed, 35 insertions, 0 deletions
diff --git a/src/list.gleam b/src/list.gleam
index 6687acf..12b7cad 100644
--- a/src/list.gleam
+++ b/src/list.gleam
@@ -3,6 +3,9 @@ import expect
pub enum Empty =
| Empty
+pub enum NotFound =
+ | NotFound
+
// Using the Erlang C BIF implementation.
//
pub external fn length(List(a)) -> Int = "erlang" "length"
@@ -279,3 +282,35 @@ test foldr {
|> foldr(_, [], fn(x, acc) { [x | acc] })
|> expect:equal(_, [1, 2, 3])
}
+
+pub fn find(haystack, f) {
+ case haystack {
+ | [] -> Error(NotFound)
+ | [x | rest] ->
+ case f(x) {
+ | Ok(x) -> Ok(x)
+ | _ -> find(rest, f)
+ }
+ }
+}
+
+test find {
+ let f = fn(x) {
+ case x {
+ | 2 -> Ok(4)
+ | _ -> Error(NotFound)
+ }
+ }
+
+ [1, 2, 3]
+ |> find(_, f)
+ |> expect:equal(_, Ok(4))
+
+ [1, 3, 2]
+ |> find(_, f)
+ |> expect:equal(_, Ok(4))
+
+ [1, 3]
+ |> find(_, f)
+ |> expect:equal(_, Error(NotFound))
+}