Skip to content

Commit 8a68cac

Browse files
giacomocavalierilpil
authored andcommitted
Fix implementation of list.unique
1 parent e6493af commit 8a68cac

File tree

2 files changed

+15
-2
lines changed

2 files changed

+15
-2
lines changed

CHANGELOG.md

+4
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,9 @@
11
# Changelog
22

3+
## Unreleased
4+
5+
- Fixed a bug that would result in `list.unique` having quadratic runtime.
6+
37
## v0.53.0 - 2025-01-23
48

59
- `io.print` will now work in JavaScript environments where the `process`

src/gleam/list.gleam

+11-2
Original file line numberDiff line numberDiff line change
@@ -1159,9 +1159,18 @@ fn intersperse_loop(list: List(a), separator: a, acc: List(a)) -> List(a) {
11591159
/// ```
11601160
///
11611161
pub fn unique(list: List(a)) -> List(a) {
1162+
unique_loop(list, dict.new(), [])
1163+
}
1164+
1165+
fn unique_loop(list: List(a), seen: Dict(a, Nil), acc: List(a)) -> List(a) {
11621166
case list {
1163-
[] -> []
1164-
[x, ..rest] -> [x, ..unique(filter(rest, fn(y) { y != x }))]
1167+
[] -> reverse(acc)
1168+
[first, ..rest] ->
1169+
case dict.has_key(seen, first) {
1170+
True -> unique_loop(rest, seen, acc)
1171+
False ->
1172+
unique_loop(rest, dict.insert(seen, first, Nil), [first, ..acc])
1173+
}
11651174
}
11661175
}
11671176

0 commit comments

Comments
 (0)