清单的方案和 [英] Scheme sum of list

查看:70
本文介绍了清单的方案和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,这是家庭作业,但我只是在寻找有关如何执行此操作的提示或伪代码.

First off, this is homework, but I am simply looking for a hint or pseudocode on how to do this.

我需要使用递归对列表中的所有项目进行汇总.但是,如果遇到列表中的非数字内容,则需要返回空集.这是我的尝试:

I need to sum all the items in the list, using recursion. However, it needs to return the empty set if it encounters something in the list that is not a number. Here is my attempt:

(DEFINE sum-list
  (LAMBDA (lst)
    (IF (OR (NULL? lst) (NOT (NUMBER? (CAR lst))))
      '()
      (+
        (CAR lst)
        (sum-list (CDR lst))
      )
    )
  )
)

此操作失败,因为它无法将空集添加到其他内容.通常,如果它不是数字,我只会返回0并继续处理列表.

This fails because it can't add the empty set to something else. Normally I would just return 0 if its not a number and keep processing the list.

推荐答案

我愿意这样做:

(define (mysum lst)
  (let loop ((lst lst) (accum 0))
    (cond
      ((empty? lst) accum)
      ((not (number? (car lst))) '())
      (else (loop (cdr lst) (+ accum (car lst)))))))

这篇关于清单的方案和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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