Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

clojure sequence
reverse method
community creator
clojure

How to use the reverse method in Clojure on a sequence

Chinweuba Elijah Azubuike

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)
Click "Run" to see the results. Please observe that the output sequence has the same elements as seq1 but with the order reversed. Try changing the values in seq1, click "Run" again, and observe the results.

Explanation

  • Line 3: We define a function, revers.
  • Line 4: We define a sequence named seq1 using the seq method.
  • Line 5: We use the reverse method to reverse the order of elements in seq1 and use println to print the result returned by reverse.
  • Line 6: We call the defined revers function.

RELATED TAGS

clojure sequence
reverse method
community creator
clojure

CONTRIBUTOR

Chinweuba Elijah Azubuike
RELATED COURSES

View all Courses

Keep Exploring