Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculating list cumulative sum in Haskell

Tags:

haskell

Write a function that returns the running sum of list. e.g. running [1,2,3,5] is [1,3,6,11]. I write this function below which just can return the final sum of all the values among the list.So how can i separate them one by one?

sumlist' xx=aux xx 0
    where aux [] a=a
          aux (x:xs) a=aux xs (a+x)
like image 463
CathyLu Avatar asked Jan 19 '11 06:01

CathyLu


2 Answers

I think you want a combination of scanl1 and (+), so something like

scanl1 (+) *your list here*

scanl1 will apply the given function across a list, and report each intermediate value into the returned list.

Like, to write it out in pseudo code,

scanl1 (+) [1,2,3]

would output a list like:

[a, b, c] where { a = 1, b = a+2, c = b+3 }

or in other words,

[1, 3, 6]

Learn You A Haskell has a lot of great examples and descriptions of scans, folds, and much more of Haskell's goodies.

Hope this helps.

like image 140
Zach L Avatar answered Sep 19 '22 12:09

Zach L


You can adjust your function to produce a list by simply prepending a+x to the result on each step and using the empty list as the base case:

sumlist' xx = aux xx 0
    where aux [] a = []
          aux (x:xs) a = (a+x) : aux xs (a+x)

However it is more idiomatic Haskell to express this kind of thing as a fold or scan.

like image 45
sepp2k Avatar answered Sep 21 '22 12:09

sepp2k