Skip to content

Commit

Permalink
Make list.unique loglinear instead of quadratic
Browse files Browse the repository at this point in the history
  • Loading branch information
radekm committed Nov 13, 2024
1 parent 32f29ae commit b9098ca
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 4 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

## Unreleased

- Fixed a bug where `list.unique` had quadratic complexity instead of loglinear.
- The `bit_array` module gains the `bit_size` and `starts_with` functions.
- Ths `string` module gains the `drop_start`, `drop_end`, `pad_start`,
`pad_end`, `trim_start`, and `trim_end` functions. These replace the
Expand Down
16 changes: 12 additions & 4 deletions src/gleam/list.gleam
Original file line number Diff line number Diff line change
Expand Up @@ -1166,10 +1166,18 @@ fn intersperse_loop(list: List(a), separator: a, acc: List(a)) -> List(a) {
/// ```
///
pub fn unique(list: List(a)) -> List(a) {
case list {
[] -> []
[x, ..rest] -> [x, ..unique(filter(rest, fn(y) { y != x }))]
}
let #(result_rev, _) =
// We can't use `gleam/set` here, as it would create an import cycle
// (`gleam/set` depends on `gleam/list`), so we're using `gleam/dict` instead.
list
|> fold(#([], dict.new()), fn(acc, x) {
let #(result_rev, seen) = acc
case dict.has_key(seen, x) {
False -> #([x, ..result_rev], dict.insert(seen, x, Nil))
True -> #(result_rev, seen)
}
})
result_rev |> reverse
}

/// Sorts from smallest to largest based upon the ordering specified by a given
Expand Down

0 comments on commit b9098ca

Please sign in to comment.