简体   繁体   English

在Scheme中添加嵌套列表的总和

[英]Adding The Sum Of Nested List In Scheme

I'm using scheme. 我正在使用计划。 I'm having no problems in finding the sum of a certain list but I'm quite having trouble in adding the sum when a list has a list in it or AKA Nested List. 我找到某个列表的总和没有问题,但是当列表中有列表或AKA嵌套列表时,我很难添加总和。

(define (my-summation li)
(if (null? li)
  0
  ((if (list? (car li)) (my-summation (car li))
  (+ (car li) (my-summation (cdr li)))))))

This was my input and this was the result of the error. 这是我的输入,这是错误的结果。 Scheme is my weakness since it involves recursion but I can't seem to find the problem. Scheme是我的弱点,因为它涉及递归,但我似乎无法找到问题。

> (my-summation '(6 3 -2 5 '(4 2 -3) 4 )) 
function call: expected a function after the open parenthesis, but received -3

Its in the parentheses, you have an extra set around the if . 它在括号中,你有一个额外的设置围绕if Also you don't need to quote a list when it is in a quoted list. 此外,当它在引用列表中时,您不需要引用列表。 And the (list? (car li)) case was incorrect, it should sum the element and the rest of the list. 并且(list? (car li))案例不正确,它应该对元素和列表的其余部分求和。

(define (my-summation li)
  (if (null? li)
      0
      (if (list? (car li))
          (+ (my-summation (car li)) (my-summation (cdr li)))
          (+ (car li) (my-summation (cdr li))))))

(my-summation '(6 3 -2 5 (4 2 -3) 4))

Results in a sum of 19 . 结果总和为19

An alternative solution: 替代解决方案:

(define (sum-list xs)
  (define (loop sum-so-far xs)
    (cond
      [(null? xs)        sum-so-far]                              ; no-more-elements
      [(pair? (car xs))  (loop (+ sum-so-far (sum-list (car xs))) ; the first element is a sublist
                               (cdr xs))]                         ;   so sum-list computes its sum 
      [else              (loop (+ sum-so-far (car xs))            ; the first element is a number
                               (cdr xs))]))                        ;  so it is added directly
  (loop 0 xs))

(sum-list '(6 3 -2 5 (4 2 -3) 4)) ; note: no quote in the middle

; ==> 19

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM