Skip to content

Commit

Permalink
Make list.unique logarithmic instead of quadratic
Browse files Browse the repository at this point in the history
  • Loading branch information
radekm committed Aug 14, 2024
1 parent 894bc95 commit 236a899
Showing 1 changed file with 12 additions and 5 deletions.
17 changes: 12 additions & 5 deletions src/gleam/list.gleam
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import gleam/float
import gleam/int
import gleam/order.{type Order}
import gleam/pair
import gleam/set

/// Counts the number of elements in a given list.
///
Expand Down Expand Up @@ -1151,7 +1152,7 @@ pub fn intersperse(list: List(a), with elem: a) -> List(a) {

/// Removes any duplicate elements from a given list.
///
/// This function returns in loglinear time.
/// This function returns in logarithmic time.
///
/// ## Examples
///
Expand All @@ -1161,10 +1162,16 @@ pub fn intersperse(list: List(a), with elem: 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, _) =
xs
|> list.fold(#([], set.new()), fn(acc, x) {
let #(result_rev, seen) = acc
case set.contains(seen, x) {
False -> #([x, ..result_rev], set.insert(seen, x))
True -> #(result_rev, seen)
}
})
result_rev |> list.reverse
}

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

0 comments on commit 236a899

Please sign in to comment.