Skip to content

Instantly share code, notes, and snippets.

@ericnormand
Created March 30, 2021 13:21
Show Gist options
  • Select an option

  • Save ericnormand/c2a1dd5f9dd04cd0dd9919d464e6fadf to your computer and use it in GitHub Desktop.

Select an option

Save ericnormand/c2a1dd5f9dd04cd0dd9919d464e6fadf to your computer and use it in GitHub Desktop.
420 PurelyFunctional.tv Newsletter

Unique elements

There's a function in Clojure called distinct that removes duplicates from a sequence. Your task is to write a function called uniques that removes elements that appear twice.

Examples

(uniques []) ;=> ()
(uniques [1 2 3]) ;=> (1 2 3)
(uniques [1 1 2 3]) ;=> (2 3)
(uniques [1 2 3 1 2 3]) ;=> ()
(uniques [1 2 3 2]) ;=> (1 3)

Thanks to this site for the challenge idea where it is considered Medium in Python. The problem has been modified from the original.

Please submit your solutions as comments on this gist.

To subscribe: https://purelyfunctional.tv/newsletter/

@sztamas

sztamas commented Mar 31, 2021

Copy link
Copy Markdown
(defn uniques [coll]
  (let [freqs   (frequencies coll)
        unique? (comp zero? dec freqs)]
    (filter unique? coll)))

@filippocostalli

Copy link
Copy Markdown
(defn uniques [c]
  (->> c
       (frequencies)
       (filter (fn [[k v]] (< v 2)))
       (map (fn [[k v]] k))))

@sim-f

sim-f commented Apr 5, 2021

Copy link
Copy Markdown
(defn has-two [freq-map e]
  (if (not= (get freq-map e)
         2)
    true
    false))

(defn uniques [input]
  (let [freq-map (frequencies input)]
    (filter #(has-two freq-map %) input)))

@vmpj

vmpj commented Apr 5, 2021

Copy link
Copy Markdown
(defn uniques [s]
(->> s
  frequencies
  (filter #(= 1 (second %)))
  (map first)))

@fahadbuddy

fahadbuddy commented Apr 6, 2021

Copy link
Copy Markdown
(defn uniques [xs]
  (let [freqs (frequencies xs)]
    (filter (comp #{1} freqs) xs)))

I am trying to understand this solution. What does this mean?

#{1} freqs

a hashset is being applied to a map? Could someone please help elaborate?

@pwojnowski

Copy link
Copy Markdown

This is simple, fast, preserves the order, and wins code-golf (I guess), but doesn't work in ClojureScript 😉

(defn uniques [xs]
    (seq (java.util.LinkedHashSet. xs)))

@burnall

burnall commented Apr 6, 2021

Copy link
Copy Markdown

@fahadbuddy #{1} is a set.
(your-set key) means getting a value from the set, i.e. key or nil if it is not in the set.

E.g.

(map #{1} [1 2 3]) ; => (1 nil nil)

@mchampine

Copy link
Copy Markdown

@farhadbuddy Note the use of “comp”. The set #{1} gets applied not to freqs but rather to the result of applying freqs to an element of xs.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment