3

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)
Mat
  • 202,337
  • 40
  • 393
  • 406
Serge
  • 41
  • 1
  • 3

3 Answers3

6

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

> (apply + (list 1 2 3))
6
rsm
  • 2,530
  • 4
  • 26
  • 33
2

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 x y), (foo x y z), .... . Inside foo the args will be '(), (x), (x y) or (x y z).

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.

rsm
  • 2,530
  • 4
  • 26
  • 33
Georg Fuss
  • 315
  • 2
  • 9
1

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.

Georg Fuss
  • 315
  • 2
  • 9