Skip to content

Commit

Permalink
add min/max to gleam/list
Browse files Browse the repository at this point in the history
  • Loading branch information
YilunAllenChen authored and lpil committed Dec 19, 2024
1 parent c33b734 commit a3018d0
Show file tree
Hide file tree
Showing 2 changed files with 88 additions and 0 deletions.
52 changes: 52 additions & 0 deletions src/gleam/list.gleam
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
})
}
36 changes: 36 additions & 0 deletions test/gleam/list_test.gleam
Original file line number Diff line number Diff line change
Expand Up @@ -1281,3 +1281,39 @@ pub fn shuffle_test() {
list.range(0, recursion_test_cycles)
|> list.shuffle()
}

pub fn max_test() {
[]
|> list.max(int.compare)
|> should.equal(Error(Nil))

[1, 3, 2]
|> list.max(int.compare)
|> should.equal(Ok(3))

[-1.0, 1.2, 1.104]
|> list.max(float.compare)
|> should.equal(Ok(1.2))

["a", "c", "b"]
|> list.max(string.compare)
|> should.equal(Ok("c"))
}

pub fn min_test() {
[]
|> list.min(int.compare)
|> should.equal(Error(Nil))

[1, 3, 2]
|> list.min(int.compare)
|> should.equal(Ok(1))

[-1.0, 1.2, 1.104]
|> list.min(float.compare)
|> should.equal(Ok(-1.0))

["a", "c", "b"]
|> list.min(string.compare)
|> should.equal(Ok("a"))
}

0 comments on commit a3018d0

Please sign in to comment.