From: Darrell Adams on
I am very new to LISP.

I would like to know how to return the sum, over all the elements, of a
variable length list.

I know that you can use

(+ 1 2 3 ...) to get a sum of a few items.

If I have an item of variable length as in

(setq vector '(1 2 3 ... n))

I would like to have the sum returned.

I hope this is clear enough.

Thanks,
Darrell
From: Geoffrey King on
(apply #'+ '( 1 2 3))

Darrell Adams wrote:
> I am very new to LISP.
>
> I would like to know how to return the sum, over all the elements, of a
> variable length list.
>
> I know that you can use
>
> (+ 1 2 3 ...) to get a sum of a few items.
>
> If I have an item of variable length as in
>
> (setq vector '(1 2 3 ... n))
>
> I would like to have the sum returned.
>
> I hope this is clear enough.
>
> Thanks,
> Darrell
From: Geoffrey Summerhayes on
Geoffrey King <lordergeoff...(a)optushome.com.au> wrote:
>
> (apply #'+ '( 1 2 3))
>

Safer, due to LAMBDA-PARAMETERS-LIMIT, is:

(reduce #'+ '(1 2 3) :initial-value 0)

--
Geoff

From: Geoffrey King on
Why the ":initial-value 0" ?

Geoffrey Summerhayes wrote:
> Geoffrey King <lordergeoff...(a)optushome.com.au> wrote:
>> (apply #'+ '( 1 2 3))
>>
>
> Safer, due to LAMBDA-PARAMETERS-LIMIT, is:
>
> (reduce #'+ '(1 2 3) :initial-value 0)
>
> --
> Geoff
>
From: Pascal Bourguignon on
Geoffrey King <lordergeoffrey(a)optushome.com.au> writes:
> Darrell Adams wrote:
>> I am very new to LISP.
>> I would like to know how to return the sum, over all the elements,
>> of a variable length list.
>> I know that you can use
>> (+ 1 2 3 ...) to get a sum of a few items.
>> If I have an item of variable length as in
>> (setq vector '(1 2 3 ... n))
>> I would like to have the sum returned.
>> I hope this is clear enough.
>
> (apply #'+ '( 1 2 3))


No. This is a FAQ. The answer is: (reduce (function +) list)

--
A: Because it messes up the order in which people normally read text.
Q: Why is top-posting such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
__Pascal Bourguignon__ http://www.informatimago.com/