|
1 | | -import gleam/io |
2 | 1 |
|
3 | 2 | import gleam/int |
4 | 3 | import gleam/option |
@@ -73,6 +72,28 @@ pub fn by(key: fn(a) -> b, cmp: fn(b, b) -> order.Order) -> Comparator(a) { |
73 | 72 | fn(x, y) { cmp(key(x), key(y)) } |
74 | 73 | } |
75 | 74 |
|
| 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 | + |
76 | 97 | /// Build a comparator for `Option(a)` given: |
77 | 98 | /// - `none_order`: the `order.Order` to use when comparing `None` with `Some(_)`. |
78 | 99 | /// 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)) |
210 | 231 | pub fn list_compare(elem_cmp: fn(a, a) -> order.Order) -> Comparator(List(a)) { |
211 | 232 | fn(xs, ys) { list_compare_go(elem_cmp, xs, ys) } |
212 | 233 | } |
213 | | - |
214 | | -pub fn main() -> Nil { |
215 | | - io.println("Hello from cmp!") |
216 | | -} |
|
0 commit comments