Lisp - Reversing List



Lisp provides reverse and nreverse functions which can be used to reverse lists. reverse function returns a new list while nreverse modifies the original list.

Example - Reverse a list using reverse method.

Syntax - reverse function

reverse list

Arguments

  • list− list to be reversed.

Returns

This function returns a new reversed list.

Following example reverses a list and prints the same. reverse method returns the reversed list and keep original list intact.

main.lisp

; define a list
(defvar myList '(a b c d e f))
; reverse a list
(setf reversedList (reverse myList))
; print the reversed list
(print reversedList)
(terpri)
; print the original list
(print myList)

Output

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

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

Example - Reversing list using nreverse method.

Syntax - nreverse function

nreverse list

Arguments

  • list− list to be reversed.

Returns

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

Following example reverses a list and prints the same. nreverse method reverses the original list.

main.lisp

; define a list
(defvar myList '(a b c d e f))
; reverse the list and print
(nreverse myList)
(print myList)
(terpri)
; print the original list
(print myList)

Output

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

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