简体   繁体   中英

sum of a list in scheme

I'm beginner in functional programming and scheme language.

I found a way to build the sum of a list:

(define (sum lst)
  (if (empty? lst)
      0
      (+ (car lst) (sum (cdr lst)))))

(sum (list 1 2 3))

My question is: is there a way to build the sum of a list without a extra function like sum, just using the "+" function like this:

(+ 1 2 3)

You can apply list of arguments to a function. So in this case you can:

> (apply + (list 1 2 3))
6

The reference for MIT/Gnu-Scheme says, that + takes ANY number of arguments. I am sure, that this standard.

In general:

(define (foo . args) ....)

is used like (foo) or (foo x) or (foo xy) , (foo xyz) , .... . Inside foo the args will be '() , (x) , (xy) or (xyz) .

See exercise 2.20 in SICP or MIT/Scheme Reference 9.2 chap 2.1

This means:

For the arithmetic procedures + , * , - and / your procedure is not necessary, because they are defined for any number of arguments, including zero and one. This is also true for some other built-in procedures. For your own procedures you can use the dotted-tail notation.

You can download the MIT/Scheme Reference from the GNU-Pages. I think it helps for all implementation of Scheme, because extension of the standard are described. Most parts are easy to read.

Common Lisp programmers should look to [ http://www.gigamonkeys.com/book/functions.html] .

Here you must use &rest instead of >.< (defun + (&rest numbers) ...)

Both lisp-dialects know default, optional and rest parameters.

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