Ibrahim Muhammad
Ibrahim Muhammad

Reputation: 2896

Sum of numbers in a list using Scheme

I want to sum the numbers in a list without using recursion. I know you can sum a list of numbers like this

(+ num1 num2 ... numN)

but what if you have a list L which equals to '(num1 num2 ... numN) is there a way to make + take the numbers in this list as arguments. I need to do this without recursion or helper functions.

Upvotes: 3

Views: 3799

Answers (2)

newacct
newacct

Reputation: 122439

The general answer to the question you seem to be asking -- how to take a list and use it as the arguments -- is apply, as Chris Jester-Young answered.

However, for this particular question, there might some other considerations. You may want to sum lists of arbitrary size. However, implementations often have some limit of the number of arguments you can call a function with. A more reliable solution may be to use some kind of fold function (various implementations have different fold functions) to fold + over the list.

Upvotes: 3

C. K. Young
C. K. Young

Reputation: 223023

Sure, just use apply:

(apply + '(1 2 3 4 5 6))   ; same as (+ 1 2 3 4 5 6)
(apply + 1 2 3 '(4 5 6))   ; ditto
(apply + 1 2 3 4 5 '(6))   ; ditto
(apply + 1 2 3 4 5 6 '())  ; ditto

Upvotes: 11

Related Questions