计划当您有结构和列表列表时,如何对列表中的数字求和 [英] scheme how do you sum numbers in a list when you have structures and list of lists

查看:33
本文介绍了计划当您有结构和列表列表时,如何对列表中的数字求和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

;; An ATOM is one of: 
;; -- Symbol
;; -- String 
;; -- Number

;; An SEXP (S-expression) is one of: 
;; -- empty 
;; -- (cons ATOM SEXP)
;; -- (cons SEXP SEXP)

所以我正在尝试总结 SEXP 中的所有数字!这是我的代码,

So i'm trying to sum up all the numbers in SEXP! Here's my code,

;; sum-numbers: sexp -> Number

(define (sum-numbers sexp)
(cond 
  [(empty? sexp) 0]
  [(ATOM? (first sexp)) (+ (atom-sum-numbers (first sexp))
                           (sum-numbers (rest sexp)))]
  [(SEXP? (first sexp)) (+ (sum-numbers (first sexp))
                           (sum-numbers (rest sexp)))]))

;; atom-sum-numbers: Atom -> Number 
(define (atom-sum-numbers a)
    (cond 
       [(symbol? a) 0]
       [(number? a) (+ (ATOM-number a)
                    (atom-sum-numbers a))]
       [(string? a) 0]))

然而,错误说cond:所有问题结果都是错误的.我想知道那里发生了什么.

However, an error says cond: all question results were false. I'm wondering what happened there.

推荐答案

您将结构访问器过程与列表操作过程混合在一起,这是行不通的 - 您必须保持一致,如果使用结构,则必须使用结构的自己的程序.

You're mixing struct accessor procedures with list manipulation procedures, that won't work - you have to be consistent, if using structs then you must use the struct's own procedures.

另外,你的 ATOM 结构看起来是错误的,事实上,它是这样说的:一个原子由一个符号、一个字符串一个数字(三件事,而不仅仅是其中之一!).当然,symbol?number?string? 谓词对该结构不起作用,这就是为什么 cond 抱怨所有条件都是假的.

Also, your ATOM structure looks wrong, as it is, it's saying: an atom is made up of a symbol, a string and a number (the three things, not just one of them!). Of course, the symbol?, number? and string? predicates won't work for that struct, that's why cond is complaining that all of the conditions are false.

我建议您尝试其他方法,其中原子实际上是原子,而不是结构.否则,您将不得不重新考虑 ATOM 结构,其当前形式将无法按照您想象的方式工作.例如,这将起作用:

I suggest you try something else, where the atoms are really atoms, not structs. Otherwise you'll have to rethink the ATOM structure, in its current form won't work in the way you imagine. For instance, this will work:

(define (sum-numbers sexp)
  (cond 
    [(empty? sexp) 0]
    [(SEXP? (SEXP-ATOM sexp)) (+ (sum-numbers (SEXP-ATOM sexp))
                                 (sum-numbers (SEXP-SEXP sexp)))]
    [else (+ (atom-sum-numbers (SEXP-ATOM sexp))
             (sum-numbers (SEXP-SEXP sexp)))]))

(define (atom-sum-numbers a)
  (cond 
    [(symbol? a) 0]
    [(number? a) a]
    [(string? a) 0]))

让我们测试一下,注意原子是普通的 Scheme 原子,而不是 ATOM 结构的实例:

Let's test it, and notice how atoms are plain Scheme atoms, not instances of the ATOM struct:

(sum-numbers 
 (make-SEXP 'x 
            (make-SEXP 7
                       (make-SEXP "a" 
                                  '()))))
=> 7

这篇关于计划当您有结构和列表列表时,如何对列表中的数字求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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