Scheme function that returns the odd-numbered elem

2019-06-05 09:02发布

问题:

I have to create a recursive Scheme function for my programming class that will take all the odd-numbered elements of a list, and then return them in reversed order.

I have a function for reversing a list, and another function for getting the odd-numbered elements, but can't figure out how to combine the two into a new function, as they both are recursive.

It has to be one function that doesn't call any functions other than itself. It can not call odd or reverse, and it has to have the same functionality as calling both would have.

Odd Function:

(define (odd lst)
    (if (null? lst)                   
        '()                          
        (cons (car lst)              
              (odd (cddr lst)))))

Reverse Function:

(define (reverse lst)
   (if (null? lst)
       '()
       (append (reverse (cdr lst))
               (list (car lst)))))

Any help would be appreciated!

回答1:

Your reverse mostly does what you want, except that it includes the even-numbered elements as well, in its result.

For example, if you were trying to reverse (1 2 3 4 5 6 7) with your reverse, it would make a recursive call to reverse the list (2 3 4 5 6 7); if you could get it to leave off the 2 from that recursive call, you'd be in good shape here (although you'll have to deal with an edge case which you'll discover quickly enough).