Jump to content

Cumultative sum of a list of values


jbreard

Recommended Posts

Hello everyone,

 

Do anyone know how to calculate efficiently the cumulative sum list of a list of value without using a loop explicitly ?

 

Given a list of value (a b c d e...), I want to calculate the list (a (a+b) (a+b+c) (a+b+c+d)....). I'm sure there is a simple way to do such a thing with recursion but I can't quite understand yet how these particuliar functions work.

 

I searched the forum and I found approaching topics but nothing that I could understand enough to perform such a function.

 

Thanks a lot and have a great day,

 

Jacques

Link to comment
Share on other sites

(defun _sums (l / s)
  (setq s 0)
  (mapcar '(lambda (x) (setq s (+ s x))) l)
)

 

_$ (_sums '(1 2 3 4))
(1 3 6 10)
_$ 

 

  • Like 1
Link to comment
Share on other sites

It works like a charm ! Thanks so much Stefan

 

Now I will have to understand how it works so well.

 

Thanks again,

 

Jacques

Link to comment
Share on other sites

Another, for fun, recursive & inefficient -

(defun trinum ( l )
    (if (cdr l)
        (cons (car l) (trinum (cons (+ (car l) (cadr l)) (cddr l))))
        l
    )
)

 

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Unfortunately, your content contains terms that we do not allow. Please edit your content to remove the highlighted words below.
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...