Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing duplicates in clojure

Tags:

clojure

I have a sequence and trying to remove duplicates

case 1: 

(vec (into #{} [1 1 2 2 3 3])) ; => [1 2 3]


case 2:

(distinct [1 1 2 2 3 3]) ; => [1 2 3]
  1. Both cases are bringing the results, so which one is better to use?
  2. What's the difference between on those?
like image 791
Nireekshan Avatar asked Jan 28 '26 00:01

Nireekshan


1 Answers

As for differences, jas covered most of them in his comment:

  1. distinct is lazy
  2. distinct with no arguments is a transducer
  3. distinct maintains order

As for which one is preferred, distinct is for the above reasons, but also because it explains what you need. I forget which Lisp book talked about this (might have been Let Over Lambda), but when given the choice between two similar functions, prefer the one that's more specific. distinct explains that you want distinct elements. (into #{} xs) might produce distinct values, but it also allows your intent to be misunderstood. Someone could easily think you wanted a set for some reason. distinct narrows down the why.

like image 65
exupero Avatar answered Jan 30 '26 18:01

exupero



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!