Jump to content

Sum of numbers in a list


Recommended Posts

Posted

Hello fellow hackers,

 

This post probably doesn't reflect the title as what you think it is, but I think it will still do. What I want to achieve is from a list of integers or reals as example below:

 

(1 2 3 4 5 6 7)

 

into:

 

(1 3 6 10 15 21 28)

 

where the value on the nth index is the sum of all the integers from the first index to that index. Anyone know a good way to achieve this?

I'm hoping to use a simple mapcar function but nothing's coming to my head. 

 

(P.S. I've run an error handle so that only integers and reals are allowed in the list.)

 

Thanks,

Jonathan Handojo

Posted (edited)
(defun foo ( l )
    (defun bar ( l )
        (if l (cons (apply '+ l) (bar (cdr l))))
    )
    (reverse (bar (reverse l)))
)
_$ (foo '(1 2 3 4 5 6 7))
(1 3 6 10 15 21 28)

 

Edited by Lee Mac
  • Like 1
Posted (edited)
(defun foo ( l / x )
    (setq x 0)
    (mapcar '(lambda ( y ) (setq x (+ x y))) l)
)
_$ (foo '(1 2 3 4 5 6 7))
(1 3 6 10 15 21 28)

 

Edited by Lee Mac
Posted
2 minutes ago, Lee Mac said:

(defun foo ( l / x )
    (setq x 0)
    (mapcar '(lambda ( y ) (setq x (+ x y))) l)
)

_$ (foo '(1 2 3 4 5 6 7))
(1 3 6 10 15 21 28)

 

 

That was quick! What a nice method, I thought I would've used apply on some case, but that's a nice trick. Thanks Lee!

Posted

Not elegant as Lee's

; (foo '(1 2 3 4 5 6 7))
(defun foo ( L )
  ('( (f) (cdr (f 0 L)))
    '( (c L)
      (if L
        (cons c (f (+ c (car L)) (cdr L)))
        (list c)
      )
    )
  )
)

 

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...