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 Nov 13, 2024
1 parent 32f29ae commit 59a5293
Showing 1 changed file with 10 additions and 4 deletions.
14 changes: 10 additions & 4 deletions src/gleam/list.gleam
Original file line number Diff line number Diff line change
Expand Up @@ -1166,10 +1166,16 @@ fn intersperse_loop(list: List(a), separator: a, acc: List(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 59a5293

Please sign in to comment.