aboutsummaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
authorYilunAllenChen <allenchenyilun1999@gmail.com>2024-12-15 14:43:01 -0600
committerLouis Pilfold <louis@lpil.uk>2024-12-19 11:58:24 +0000
commita3018d0ab4e5d6ac0fa381d7798397554f1e5a91 (patch)
treea80016653c76d3b690a4fcc29d09ca7f004da152 /src
parentc33b7341838d9286903c39697c82fc81f30fd437 (diff)
downloadgleam_stdlib-a3018d0ab4e5d6ac0fa381d7798397554f1e5a91.tar.gz
gleam_stdlib-a3018d0ab4e5d6ac0fa381d7798397554f1e5a91.zip
add min/max to gleam/list
Diffstat (limited to 'src')
-rw-r--r--src/gleam/list.gleam52
1 files changed, 52 insertions, 0 deletions
diff --git a/src/gleam/list.gleam b/src/gleam/list.gleam
index 5f537b9..2d5b624 100644
--- a/src/gleam/list.gleam
+++ b/src/gleam/list.gleam
@@ -2311,3 +2311,55 @@ fn do_shuffle_by_pair_indexes(
float.compare(a_pair.0, b_pair.0)
})
}
+
+/// Takes a list and a comparator, and returns the maximum element in the list
+///
+///
+/// ## Example
+///
+/// ```gleam
+/// range(1, 10) |> list.max(int.compare)
+/// // -> Ok(10)
+/// ```
+///
+/// ```gleam
+/// ["a", "c", "b"] |> list.max(string.compare)
+/// // -> Ok("c")
+/// ```
+pub fn max(
+ over list: List(a),
+ with compare: fn(a, a) -> Order,
+) -> Result(a, Nil) {
+ reduce(over: list, with: fn(acc, other) {
+ case compare(acc, other) {
+ order.Gt -> acc
+ _ -> other
+ }
+ })
+}
+
+/// Takes a list and a comparator, and returns the minimum element in the list
+///
+///
+/// ## Example
+///
+/// ```gleam
+/// range(1, 10) |> list.int(int.compare)
+/// // -> Ok(1)
+/// ```
+///
+/// ```gleam
+/// ["a", "c", "b"] |> list.int(string.compare)
+/// // -> Ok("a")
+/// ```
+pub fn min(
+ over list: List(a),
+ with compare: fn(a, a) -> Order,
+) -> Result(a, Nil) {
+ reduce(over: list, with: fn(acc, other) {
+ case compare(acc, other) {
+ order.Lt -> acc
+ _ -> other
+ }
+ })
+}