Reversing lists
eharetea

Reversing a list in scheme using iterative and recursive processes.

How to reverse a list in scheme.

Date Created:Tuesday September 16th, 2008 10:29 AM
Date Modified:Friday October 03rd, 2008 06:15 PM

#|
* THIS IS THE ITERATIVE CALL WITH A COUNTER
|#


(define (rev1 x)
   (helper x nil (count x)) 
)

(define (helper1 x y n)
  (if (= n 0)
      y
      (helper x (append y (list (item n x))) (- n 1))
  )
)

#|
* THIS IS THE ITERATIVE CALL WITHOUT A COUNTER
|#


(define (rev x)
   (helper x nil) 
)

(define (helper x y)
  (if (null? x)
      y
      (helper (cdr x) (cons (car x) y) )
  )
)


#|
* THIS IS THE RECURSIVE CALL
|#

(define (reverse a)
  (if (empty? a)
       nil
       (append (reverse (cdr a)) (list (car a)) )
  )
)

(define a (list 'a 'b 'c))

#|
* HERE IS SOME EXAMPLE OUTPUT
|#

(rev a)
(c b a)

(reverse a)
(c b a)


; DEEP RECURSIVE 

(define (deep-reverse lst)
  (if (atom? lst)
      lst
      (append
            (deep-reverse (cdr lst))
            (list (deep-reverse (car lst))
      )
   )
)



Downloads:
Download: reverse.scm 691 B
Download: deep.scm 192 B

Please login or Click Here to register for downloads
Creative Commons License
Reversing lists by Dan Lynch
is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 United States License
Based on a work at www.3daet.com
Permissions beyond the scope of this license may be available at http://www.3daet.com