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 bd0da5a
Showing 1 changed file with 11 additions and 5 deletions.
16 changes: 11 additions & 5 deletions src/gleam/list.gleam
Original file line number Diff line number Diff line change
Expand Up @@ -1151,7 +1151,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 +1161,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, _) =
list
|> fold(#([], dict.new()), fn(acc, x) {
let #(result_rev, seen) = acc
case dict.has_key(seen, x) {
False -> #([x, ..result_rev], dict.insert(seen, x, Nil))
True -> #(result_rev, seen)
}
})
result_rev |> reverse
}

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

0 comments on commit bd0da5a

Please sign in to comment.