What is the distinct method in Clojure?

Overview

The distinct method in Clojure returns a sequence only containing unique values. A Clojure sequence is a data storage structure that holds a collection of data objects. It can be seen as a logical list. The seq method builds a sequence.

The code snippet below shows the use of the distinct method:

(distinct seq1)
seq1 is the sequence being inputted.

The distinct method accepts one input argument: a Clojure sequence. The input argument in the code snippet above is seq1. The distinct method returns a sequence containing unique values. When the code snippet is executed, it returns a sequence containing all unique values in seq1. Let’s look at an example.

Example

(ns clojure.examples.example
(:gen-class))
(defn distinctt []
(def seq1 (seq [1 2 8 9 1 0 6 8 2]))
(println (distinct seq1)))
(distinctt)

Explanation

  • Line 3: We define a function, distinctt.
  • Line 4: We define a sequence named seq1 using the seq method.
  • Line 5: We use the distinct method to extract unique values in seq1 and use println to print the result returned by distinct.
  • Line 6: We call the defined distinct function.

Free Resources