Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

list.unique needs quadratic time #667

Open
radekm opened this issue Aug 6, 2024 · 1 comment · May be fixed by #678
Open

list.unique needs quadratic time #667

radekm opened this issue Aug 6, 2024 · 1 comment · May be fixed by #678

Comments

@radekm
Copy link

radekm commented Aug 6, 2024

Hello. According to the documentation list.unique returns in loglinear time.

But it's implementation

pub fn unique(list: List(a)) -> List(a) {
  case list {
    [] -> []
    [x, ..rest] -> [x, ..unique(filter(rest, fn(y) { y != x }))]
  }
}

is quadratic instead. It's especially slow if list is already unique or almost unique.

I believe that the following implementation is faster (if set.contains and set.insert are logarithmic):

pub fn unique(xs: List(a)) -> List(a) {
  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
}
@lpil
Copy link
Member

lpil commented Aug 6, 2024

Oh dear! That's certainly not what we want, especially with the incorrect documentation. Would you mind making a pull request? Thank you

@radekm radekm linked a pull request Aug 14, 2024 that will close this issue
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants