Skip to content

Commit

Permalink
Fix implementation of list.unique
Browse files Browse the repository at this point in the history
  • Loading branch information
giacomocavalieri authored and lpil committed Jan 25, 2025
1 parent e6493af commit 8a68cac
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 2 deletions.
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
# Changelog

## Unreleased

- Fixed a bug that would result in `list.unique` having quadratic runtime.

## v0.53.0 - 2025-01-23

- `io.print` will now work in JavaScript environments where the `process`
Expand Down
13 changes: 11 additions & 2 deletions src/gleam/list.gleam
Original file line number Diff line number Diff line change
Expand Up @@ -1159,9 +1159,18 @@ fn intersperse_loop(list: List(a), separator: a, acc: List(a)) -> List(a) {
/// ```
///
pub fn unique(list: List(a)) -> List(a) {
unique_loop(list, dict.new(), [])
}

fn unique_loop(list: List(a), seen: Dict(a, Nil), acc: List(a)) -> List(a) {
case list {
[] -> []
[x, ..rest] -> [x, ..unique(filter(rest, fn(y) { y != x }))]
[] -> reverse(acc)
[first, ..rest] ->
case dict.has_key(seen, first) {
True -> unique_loop(rest, seen, acc)
False ->
unique_loop(rest, dict.insert(seen, first, Nil), [first, ..acc])
}
}
}

Expand Down

0 comments on commit 8a68cac

Please sign in to comment.