Lisp - Reversing Sequence



Lisp provides reverse and nreverse functions which can be used to reverse lists, vectors and strings. reverse function returns a new sequence while nreverse modifies the original sequence. As string are immutable, nreverse will not work on string.

Syntax - reverse function

reverse sequence

Arguments

  • sequence− sequence to be reversed.

Returns

This function returns a new reversed sequence.

Example - Reverse a list

Following example reverses a list and prints the same.

main.lisp

; reverse a list
(setf reversedList (reverse '(a b c d e f)))

; print the reversed list
(print reversedList)

Output

When you execute the code, it returns the following result −

(F E D C B A) 

Example - Reverse a Vector

Following example reverses a vector and prints the same.

main.lisp

; reverse a vector
(setf reversedVector (reverse #(a b c d e f)))

; print the reversed vector
(print reversedVector)

Output

When you execute the code, it returns the following result −

#(F E D C B A) 

Example - Reverse a String

Following example reverses a string and prints the same.

main.lisp

; reverse a string
(setf reversedString (reverse "abcdef"))

; print the reversed string
(print reversedString)

Output

When you execute the code, it returns the following result −

"fedcba"

Syntax - nreverse function

nreverse sequence

Arguments

  • sequence− sequence to be reversed.

Returns

This function modifies a new reversed sequence instead of returning a new reversed sequence.

Example - Reversing lists and Vectors with modification

Following example

main.lisp

; define a list
(defvar myList '(a b c d e f))

; define a vector
(defvar myVector #(a b c d e f))

; define a string
(defvar myString "abcdef")

; reverse the list and print
(nreverse myList)
(print myList)

; reverse the vector and print
(nreverse myVector)
(print myVector)

Output

When you execute the code, it returns the following result −

(F E D C B A) 
#(F E D C B A) 
Advertisements