The Scheme Programming Language

List Sum


Click below to go directly to a specific section:
Description| Source Code| Program Notes

Description

Scheme is an imperative language that favors recursion over iteration. The basic data structure is the list. In Scheme, "car" returns the first element of a list and "cdr" returns the remaining elements of the list There is no need for an "iterator class" or pointers, as in C++. In this program cdr recursion is used as an iterator, moving from element to element in the list. The result from each recursive call becomes the input, or term, for the addition operato, there by eliminating the need for a temporary sum variable.

Source Code

;
; List Sum
; By Jerry Smith
;
(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))))))

Program Notes

This program was found in "An Introduction to Scheme" by Jerry Smith, Prentice Hall, 1988
[Back] [Home]

Last modified: 11:30 PM on 10/13/1999