简体   繁体   中英

Scheme - sum of list

I'm trying to implement a function which calc sum of list , its name is sum -

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

The above implementation gives wrong result , for example -

> (sum (list 1 2 3 4 ))
0

What I did wrong here ?

I think you swapped the then and the else part of the if :

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

In the original function, for every non-empty list, 0 is returned.

You can also use apply

(define (sum elemList) (apply + elemList))

Should give you the same results

Please refer by this link for more details. - http://groups.umd.umich.edu/cis/course.des/cis400/scheme/listsum.htm

(define(list-sum lst)
    (cond
((null ? lst)
    0)
((pair? (car lst))
    (+(list-sum (car lst)) (list-sum (cdr lst))))
(else
    (+ (car lst) (list-sum (cdr lst))))))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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