|
| 1 | +//// # Sorting lists |
| 2 | +//// |
| 3 | +//// The Gleam standard library provides functions for sorting lists and |
| 4 | +//// ordering core Gleam data types. |
| 5 | +//// |
| 6 | +//// ## Dependencies |
| 7 | +//// |
| 8 | +//// - https://hex.pm/packages/gleam_stdlib |
| 9 | + |
| 10 | +import gleam/float |
| 11 | +import gleam/int |
| 12 | +import gleam/list |
| 13 | +import gleam/order |
| 14 | +import gleam/string |
| 15 | +import gleeunit/should |
| 16 | + |
| 17 | +pub fn main_test() { |
| 18 | + // The `list.sort` function takes an additional argument, a function which is |
| 19 | + // used to determine which of any two elements in a list are bigger or |
| 20 | + // smaller. |
| 21 | + [54, 6, 34, 92, 4] |
| 22 | + |> list.sort(int.compare) |
| 23 | + |> should.equal([4, 6, 34, 54, 92]) |
| 24 | + |
| 25 | + // By convention this function is called `compare` and modules for given data |
| 26 | + // types may define this function. |
| 27 | + ["Tom", "Dick", "Harry"] |
| 28 | + |> list.sort(string.compare) |
| 29 | + |> should.equal(["Dick", "Harry", "Tom"]) |
| 30 | + |
| 31 | + // Lists are sorted from smallest to largest. If you want largest to smallest |
| 32 | + // then you can swap the arguments to the compare function. |
| 33 | + [3.4, 1.55, 10.4, 8.1] |
| 34 | + |> list.sort(fn(a, b) { float.compare(b, a) }) |
| 35 | + |> should.equal([10.4, 8.1, 3.4, 1.55]) |
| 36 | + |
| 37 | + // You can implement your own compare funtion using the `Order` type from the |
| 38 | + // `gleam/order` module. Here is a compare function which sorts strings, but |
| 39 | + // considers the string `zz-top` to be the smallest for some reason. |
| 40 | + ["electric six", "the spice girls", "abba", "zz-top", "grlwood"] |
| 41 | + |> list.sort(fn(a, b) { |
| 42 | + case a, b { |
| 43 | + "zz-top", _ -> order.Lt |
| 44 | + _, "zz-top" -> order.Gt |
| 45 | + a, b -> string.compare(a, b) |
| 46 | + } |
| 47 | + }) |
| 48 | + |> should.equal([ |
| 49 | + "zz-top", "abba", "electric six", "grlwood", "the spice girls", |
| 50 | + ]) |
| 51 | +} |
0 commit comments