Skip to content

Commit 4b42d42

Browse files
committed
Add string comparator helpers and remove main function
Introduced by_string_with and by_normalized_string helpers for flexible string comparison, allowing custom key extraction and normalization. Also removed the unused main function and redundant io import.
1 parent 1fc7bdd commit 4b42d42

1 file changed

Lines changed: 22 additions & 5 deletions

File tree

src/cmp.gleam

Lines changed: 22 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
import gleam/io
21

32
import gleam/int
43
import gleam/option
@@ -73,6 +72,28 @@ pub fn by(key: fn(a) -> b, cmp: fn(b, b) -> order.Order) -> Comparator(a) {
7372
fn(x, y) { cmp(key(x), key(y)) }
7473
}
7574

75+
/// Sugar for string comparators: pass a string key extractor and a string
76+
/// comparator (e.g. `string.compare` or `str.compare`). This helper does not
77+
/// import or depend on `str`; it only accepts a comparator function as an
78+
/// argument so the user may pass `str.compare` if they use the `str` package.
79+
pub fn by_string_with(
80+
key: fn(a) -> String,
81+
cmp: fn(String, String) -> order.Order,
82+
) -> Comparator(a) {
83+
fn(x, y) { cmp(key(x), key(y)) }
84+
}
85+
86+
/// Normalize keys with `normalize` before applying `cmp`. Useful if you want
87+
/// to apply folding/normalization (e.g. ASCII folding) prior to comparing.
88+
/// `normalize` can be any function (for example from `str/extra`).
89+
pub fn by_normalized_string(
90+
key: fn(a) -> String,
91+
normalize: fn(String) -> String,
92+
cmp: fn(String, String) -> order.Order,
93+
) -> Comparator(a) {
94+
fn(x, y) { cmp(normalize(key(x)), normalize(key(y))) }
95+
}
96+
7697
/// Build a comparator for `Option(a)` given:
7798
/// - `none_order`: the `order.Order` to use when comparing `None` with `Some(_)`.
7899
/// Use `order.Lt` for `None` < `Some`, `order.Gt` for `None` > `Some`.
@@ -210,7 +231,3 @@ fn list_compare_go(elem_cmp: fn(a, a) -> order.Order, xl: List(a), yl: List(a))
210231
pub fn list_compare(elem_cmp: fn(a, a) -> order.Order) -> Comparator(List(a)) {
211232
fn(xs, ys) { list_compare_go(elem_cmp, xs, ys) }
212233
}
213-
214-
pub fn main() -> Nil {
215-
io.println("Hello from cmp!")
216-
}

0 commit comments

Comments
 (0)