aboutsummaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
authorGiacomo Cavalieri <giacomo.cavalieri@icloud.com>2024-03-12 15:23:56 +0100
committerLouis Pilfold <louis@lpil.uk>2024-03-13 12:07:40 +0000
commit2f207523abc2e855f456bff5252c6704b48ed6c3 (patch)
tree26a39a8d749b2538306419628cde66edcfaa16f9 /src
parentb6894463caede28c8bce527c343895e28026f894 (diff)
downloadgleam_stdlib-2f207523abc2e855f456bff5252c6704b48ed6c3.tar.gz
gleam_stdlib-2f207523abc2e855f456bff5252c6704b48ed6c3.zip
Add `order.break_tie` and `order.lazy_break_tie`
Diffstat (limited to 'src')
-rw-r--r--src/gleam/order.gleam46
1 files changed, 46 insertions, 0 deletions
diff --git a/src/gleam/order.gleam b/src/gleam/order.gleam
index ad25c94..e20ea8c 100644
--- a/src/gleam/order.gleam
+++ b/src/gleam/order.gleam
@@ -133,3 +133,49 @@ pub fn min(a: Order, b: Order) -> Order {
pub fn reverse(orderer: fn(a, a) -> Order) -> fn(a, a) -> Order {
fn(a, b) { orderer(b, a) }
}
+
+/// Return a fallback `Order` in case the first argument is `Eq`.
+///
+/// ## Examples
+///
+/// ```gleam
+/// import gleam/int
+///
+/// break_tie(in: int.compare(1, 1), with: Lt)
+/// // -> Lt
+///
+/// break_tie(in: int.compare(1, 0), with: Eq)
+/// // -> Gt
+/// ```
+///
+pub fn break_tie(in order: Order, with other: Order) -> Order {
+ case order {
+ Lt | Gt -> order
+ Eq -> other
+ }
+}
+
+/// Invokes a fallback function returning an `Order` in case the first argument
+/// is `Eq`.
+///
+/// This can be useful when the fallback comparison might be expensive and it
+/// needs to be delayed until strictly necessary.
+///
+/// ## Examples
+///
+/// ```gleam
+/// import gleam/int
+///
+/// lazy_break_tie(in: int.compare(1, 1), with: fn() { Lt })
+/// // -> Lt
+///
+/// lazy_break_tie(in: int.compare(1, 0), with: fn() { Eq })
+/// // -> Gt
+/// ```
+///
+pub fn lazy_break_tie(in order: Order, with comparison: fn() -> Order) -> Order {
+ case order {
+ Lt | Gt -> order
+ Eq -> comparison()
+ }
+}