如何递归获取列表中的偶数元素 [英] How to get the even elements in a list recursively

查看:469
本文介绍了如何递归获取列表中的偶数元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个函数,该函数将返回列表中的偶数元素.

I'm trying to create a function that will return the even numbered elements in a list.

例如:

(evens '(a b c d)) 

应该返回

(b d)

下面的代码似乎适用于具有奇数个元素的列表,但是如果我给它一个具有偶数个元素的列表,那是不正确的.

The code below seems to work for lists that have and odd numbers of elements, but if I give it a list with an even number of elements, it is incorrect.

例如:

(evens '(a b c d e))

将返回

(b d)

但是:

(evens '(a b c d))

将返回

(a c)

有什么想法吗?

将我的代码更改为:

(DEFINE (evens lis)
(cond
    ((null? lis) '())   
    (else (cons (cadr lis) (evens (cdr lis))))
    ))

收到一条错误消息,说传递给安全车的物体不是一对?

Gets a error saying that the object passed to safe-car is not a pair?

推荐答案

再次最后几天.这次,我将直接给出一个答案,以使其正确:

This same question has been asked time and again over the last couple of days. I'll give a direct answer this time, to set it straight:

(define (evens lst)
  (if (or (null? lst)             ; if the list is empty 
          (null? (cdr lst)))      ; or the list has a single element
      '()                         ; then return the empty list
      (cons (cadr lst)            ; otherwise `cons` the second element
            (evens (cddr lst))))) ; and recursively advance two elements

这是首先进行一些错误检查的方法:

And here's how to do some error checking first:

(define (find-evens lst)
  (if (list? lst)
      (evens lst)
      (error "USAGE: (find-evens [LIST])")))

这篇关于如何递归获取列表中的偶数元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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