Path: utzoo!utgpu!water!watmath!clyde!att!osu-cis!tut.cis.ohio-state.edu!rutgers!apple!bionet!agate!pasteur!ames!pioneer.arc.nasa.gov!raymond From: raymond@pioneer.arc.nasa.gov.arpa (Eric A. Raymond) Newsgroups: comp.lang.lisp Subject: Re: Summing a list Message-ID: <17109@ames.arc.nasa.gov> Date: 26 Oct 88 02:51:41 GMT References: <1131@amelia.nas.nasa.gov> <5671@eagle.ukc.ac.uk> <10794@srcsip.UUCP> Sender: usenet@ames.arc.nasa.gov Reply-To: raymond@pioneer.arc.nasa.gov.UUCP (Eric A. Raymond) Organization: NASA Ames Research Center, Moffett Field, Calif. Lines: 48 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)) Ugggggh! It may seem novel but its a poor, outdated style of programming. First you waste a cons cell, make your code very obscure, and force the code to be interpreted. > But someone else says this would be faster:: > > (LET ((SUM 0)) > (DOLIST (NUM NUMLIST) > (SETQ SUM (+ SUM NUM)))) ;; or maybe (INCF SUM NUM) Or any other itertive control structure > > >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. Not necessarily. How about : (apply #'+ NUMLIST) or (reduce #'+ NUMLIST) Name: Eric A. Raymond ARPA: raymond@pioneer.arc.nasa.gov SLOW: NASA Ames Research Center, MS 244-17, Moffett Field, CA 94035 Nothing left to do but :-) :-) :-)