Skip to content

Commit bd0da5a

Browse files
committed
Make list.unique logarithmic instead of quadratic
1 parent 894bc95 commit bd0da5a

File tree

1 file changed

+11
-5
lines changed

1 file changed

+11
-5
lines changed

src/gleam/list.gleam

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1151,7 +1151,7 @@ pub fn intersperse(list: List(a), with elem: a) -> List(a) {
11511151

11521152
/// Removes any duplicate elements from a given list.
11531153
///
1154-
/// This function returns in loglinear time.
1154+
/// This function returns in logarithmic time.
11551155
///
11561156
/// ## Examples
11571157
///
@@ -1161,10 +1161,16 @@ pub fn intersperse(list: List(a), with elem: a) -> List(a) {
11611161
/// ```
11621162
///
11631163
pub fn unique(list: List(a)) -> List(a) {
1164-
case list {
1165-
[] -> []
1166-
[x, ..rest] -> [x, ..unique(filter(rest, fn(y) { y != x }))]
1167-
}
1164+
let #(result_rev, _) =
1165+
list
1166+
|> fold(#([], dict.new()), fn(acc, x) {
1167+
let #(result_rev, seen) = acc
1168+
case dict.has_key(seen, x) {
1169+
False -> #([x, ..result_rev], dict.insert(seen, x, Nil))
1170+
True -> #(result_rev, seen)
1171+
}
1172+
})
1173+
result_rev |> reverse
11681174
}
11691175

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

0 commit comments

Comments
 (0)