Nathalie D
Nathalie D

Reputation: 63

Get a reverse list "odd positioned element " in scheme

I'm a beginner in scheme , can someone please give me ideas on how to get , "the element in odd position from a list?" so ( A B C D G ) returns ( G C A). I got the list in reverse, I now need to pull every other number. Please Help. This is my code so far:

(define (list-rev lis)
  (COND
   ((NULL? lis ) '())
   ((LIST? lis)
    (append (oddrev (CDR lis)) ( list (CAR LIS))))
   (ELSE (show " USAGE: (oddrev [LIST])"))))

Upvotes: 3

Views: 885

Answers (2)

Óscar López
Óscar López

Reputation: 236142

Use an accumulator for storing the answer - this will have the effect of creating the list in reverse (there's no need to use append!) and produce a tail-recursive solution. Because this looks like homework I'll give you some hints so you can fill-in the blanks:

(define (odd-reverse lst acc)
  (cond ((null? lst)        ; if the list is null
         <???>)             ; return the empty list
        (<???>              ; if there's only one element left in the list
         (cons <???> acc))  ; cons that element with the accumulator
        (else               ; otherwise advance the recursion
         (odd-reverse <???> ; advance two positions over the list
                      (cons <???> acc))))) ; cons current element with the acc

Call it like this:

(odd-reverse '(A B C D G) '())
=> '(G C A)

If the procedure must receive only one parameter (the list), it's trivial to write another procedure that calls odd-reverse always passing a '() as the initial value for the accumulator.

Upvotes: 1

Justin Ethier
Justin Ethier

Reputation: 134255

One way is to make a single pass over the list with a function that takes two parameters: the list and a boolean value.

If the boolean value is true, then you want to cons the current element with the rest of the processed list. Otherwise, you can skip the current element and keep going. You need to flip the value of the boolean each time, since you are taking every other element.

Does that help?


Here is the code if you want, but I suggest you try it yourself first:

(define l '(A B C D G)) (define (orev lst acc) (if (null? lst) '() (if acc (cons (car lst) (orev (cdr lst) #f)) (orev (cdr lst) #t)))) (write (orev (reverse l) #t))

Upvotes: 1

Related Questions