Path: utzoo!utgpu!water!watmath!clyde!att!rutgers!cs.utexas.edu!milano!perseus!rcp From: rcp@perseus. (Rob Pettengill) Newsgroups: comp.lang.lisp Subject: Re: Summing a list Message-ID: <1457@perseus.> Date: 26 Oct 88 19:34:15 GMT References: <1131@amelia.nas.nasa.gov> <5671@eagle.ukc.ac.uk> <10794@srcsip.UUCP> Reply-To: rcp@perseus.sw.mcc.com.UUCP (Rob Pettengill) Organization: MCC Software Technology Program Lines: 54 In article <10794@srcsip.UUCP> rogers@eagle.UUCP (Brynn Rogers) writes: ; ; I Have a silly question. I need to take the sum of a list ; of numbers. ; (SETQ NUMLIST '(1 2 3 6 7)) ; This is quite simple, really, but what is the BEST way to do it? ; I like: ; ; (EVAL (CONS '+ NUMLIST)) ; ; But someone else says this would be faster:: ; ; (LET ((SUM 0)) ; (DOLIST (NUM NUMLIST) ; (SETQ SUM (+ SUM NUM)))) ;; or maybe (INCF SUM NUM) ; ; ;of course, there is always: ; ;(DEFUN SUM (NUMLIST) ; (COND ((NULL NUMLIST) 0) ; (T (+ (FIRST NUMLIST) (SUM (CDR NUMLIST)))))) ; ; I think it's obvious that the last would be slow. ; Also it's Obvious that there are Many ways to do this. ;What is the BEST (for speed and/or elegance) way to sum a list?? ; ;(I Run Gold Hills Common 3.0 on a Compaq 386/20 with a 387) ; ;Thanks, Brynn Rogers rogers@src.honeywell.com Why make life difficult? (setq numlist '(1 2 3 6 7)) (1 2 3 6 7) (apply #'+ numlist) 19 this was too easy since #'+ takes an arbitrary number of arguments. Say it took only two arguments... A general way to handle this in common lisp is with reduce: (reduce #'+ numlist) 19 ;rob Robert C. Pettengill, MCC Software Technology Program P. O. Box 200195, Austin, Texas 78720 ARPA: rcp@mcc.com PHONE: (512) 338-3533 UUCP: {ihnp4,seismo,harvard,gatech,pyramid}!ut-sally!im4u!milano!rcp