Creating a list by cumulatively adding items to another list: Haskell

I cannot find any information on a high order function that would do this. I found a link to cadd several places, but could not find any information in haskell apkell.

I just want to take a list of floats and create another list from it, adding each cumulatively. The original list always starts from scratch. Therefore, if I had a list of [0,2,5,9], I would get a list of [0,2,7,16].

accumulateTime :: [Float] -> [Float] accumulateTime (x:xs) = cadd???? 

I have other parts of this code that do something, but I cannot imagine how to make this list.

+8
haskell
source share
4 answers

It looks like you need a scanl option related to foldl but creating a list of intermediate results. Therefore, when foldl (+) 0 summarizes the list, scanl (+) 0 creates a list of partial sums. Here you probably want scanl1 (+) , which does not add extra zero at the beginning.

 Prelude> scanl1 (+) [0, 2, 5, 9] [0,2,7,16] 
+19
source share

I think the ability to translate the imperative version of this code into a functional style is a good trick that you need to have in the end. Here's how I solved this problem in one of these barbaric imperative languages:

 var acc = 0; for each x in xs: acc = x + acc yield acc 

Note that here we have two variables - a list of numbers and a moving sum. When we convert this piece of code into a functional style, we usually have to turn loops into (tail) recursions and variables into function arguments (since this is the only place they can β€œmutate”).

 accum_helper acc list 

Now we can try to work out a basic case ...

 accum_helper acc [] = ... 

... recursive case

 accum_helper acc (x:xs) = ... 

... and finally use the parent function to initialize the variable

 accumulate xs = accum_helper 0 xs 
+5
source share

Too cold than a hammar answer, but a different solution:

 accumulate list = [sum $ take n list | n <- [1 .. length list]] 
+3
source share

All Articles