How to use the reverse method in Clojure on a sequence
Clojure’s reverse method returns a sequence with its order reversed. 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 reverse method:
(reverse seq1)
seq1 is the sequence being inputted, and its reverse will be returned.
The reverse method accepts one input argument: a Clojure sequence. The input argument in the code snippet above is seq1. The reverse method returns a sequence with the same elements as the input sequence but with their order reversed. When the code snippet is executed, it returns a sequence containing all values in seq1 with their order reversed. Let’s look at an example.
Example
(ns clojure.examples.example(:gen-class))(defn revers [](def seq1 (seq [1 2 8 9 1 0 6 8 2]))(println (reverse seq1)))(revers)
Explanation
- Line 3: We define a function,
revers. - Line 4: We define a sequence named
seq1using theseqmethod. - Line 5: We use the
reversemethod to reverse the order of elements inseq1and useprintlnto print the result returned byreverse. - Line 6: We call the defined
reversfunction.