Skip to content

Commit c6a00f6

Browse files
committed
Make list.unique loglinear instead of quadratic
1 parent 32f29ae commit c6a00f6

File tree

2 files changed

+11
-4
lines changed

2 files changed

+11
-4
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
## Unreleased
44

5+
- Fixed a bug where `list.unique` had quadratic complexity instead of loglinear.
56
- The `bit_array` module gains the `bit_size` and `starts_with` functions.
67
- Ths `string` module gains the `drop_start`, `drop_end`, `pad_start`,
78
`pad_end`, `trim_start`, and `trim_end` functions. These replace the

src/gleam/list.gleam

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1166,10 +1166,16 @@ fn intersperse_loop(list: List(a), separator: a, acc: List(a)) -> List(a) {
11661166
/// ```
11671167
///
11681168
pub fn unique(list: List(a)) -> List(a) {
1169-
case list {
1170-
[] -> []
1171-
[x, ..rest] -> [x, ..unique(filter(rest, fn(y) { y != x }))]
1172-
}
1169+
let #(result_rev, _) =
1170+
list
1171+
|> fold(#([], dict.new()), fn(acc, x) {
1172+
let #(result_rev, seen) = acc
1173+
case dict.has_key(seen, x) {
1174+
False -> #([x, ..result_rev], dict.insert(seen, x, Nil))
1175+
True -> #(result_rev, seen)
1176+
}
1177+
})
1178+
result_rev |> reverse
11731179
}
11741180

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

0 commit comments

Comments
 (0)