计划函数,从列表中反向返回奇数元素 [英] Scheme function that returns the odd-numbered elements from a list in reverse

查看:60
本文介绍了计划函数,从列表中反向返回奇数元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须为我的编程类创建一个递归Scheme函数,该函数将获取列表中所有奇数元素,然后以相反的顺序返回它们.

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.

我有一个用于反转列表的函数,还有一个用于获取奇数元素的函数,但是无法弄清楚如何将两者组合成一个 new 函数,因为它们都是递归的.

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.

它必须是一个一个函数,该函数不能调用自身以外的任何函数.它不能调用oddreverse,并且必须具有与调用两者相同的功能.

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.

奇功能:

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

反向功能:

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

任何帮助将不胜感激!

推荐答案

您的reverse主要执行您想要的操作,但它的结果中还包括偶数元素.

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

例如,如果您尝试使用reverse反转(1 2 3 4 5 6 7),则会进行递归调用来反转列表(2 3 4 5 6 7);如果您可以让它离开那个递归调用中的2,那么您的状态会很好(尽管您必须处理一个很快就会发现的边缘情况)足够).

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

这篇关于计划函数,从列表中反向返回奇数元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆