方案-对列表中偶数值元素的平方求和 [英] Scheme - sum the squares of even-valued elements in a list

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

问题描述

我希望能够对列表中偶数元素的平方求和,但是我当前的代码仅对元素求和,而不对平方求和.有人知道可以进行任何修改以求和列表中偶数值元素的平方吗?

I want to be able to sum the squares of the even elements in the list, however my current code only sums the elements, not the squares. Does anyone know of any modifications that can be made to make this to sum the squares of the even-valued elements in the list?

(define (sum elemList)
  (if
    (null? elemList)
    0
    (+ (car elemList) (sum (cdr elemList)))
  )
)

我的输入是:

(sum-evens (list 1 2 3 4))

输出为:

20

哪个是(2*2) + (4*4).

如果可能,最好同时查看递归和迭代解决方案. 有什么想法吗?

If possible, it would be good to see both a recursive and iterative solution. Any ideas?

推荐答案

有两种可能性,要么我们从头开始实现递归:

There are two possibilities, either we implement the recursion from scratch:

(define (sum elemList)
  (cond ((null? elemList) 0)
        ((even? (car elemList))
         (+ (* (car elemList) (car elemList))
            (sum (cdr elemList))))
        (else (sum (cdr elemList)))))

或者我们使用内置过程,根据需要定义帮助程序.这种策略被称为使用序列作为常规接口" :

Or we use built-in procedures, defining helpers as needed. This strategy is known as using "sequences as conventional interfaces":

(define (square x)
  (* x x))

(define (sum elemList)
  (apply +
         (map square
              (filter even? elemList))))

在Scheme中,首选方法是第二种方法,因为当我们拥有已经为我们完成工作的程序时,我们一定不能重新发明轮子.无论哪种方式,它都能按预期工作:

In Scheme, the preferred way is the second one, because we must not reinvent the wheel when we have procedures that already do the job for us. Either way, it works as expected:

(sum '(1 2 3 4 5 6 7 8 9 10))
=> 220

这篇关于方案-对列表中偶数值元素的平方求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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