Scheme function that returns the odd-numbered elements from a list in reverse

人盡茶涼 提交于 2019-12-23 03:21:28

问题


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).



来源:https://stackoverflow.com/questions/49723995/scheme-function-that-returns-the-odd-numbered-elements-from-a-list-in-reverse

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!