8

I cant seem to find any information on a high order function that would do this. I found a reference to cadd a few places but could not find any information in a haskell api.

I just simply want to take a list of floats, and create another list from it by cumulatively adding each. The original list will always start with zero. So 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 doing things but i cant seem how to make this list.

0

4 Answers 4

23

Sounds like you want a variant of scanl, which is related to foldl, but creates a list of intermediate results. So while foldl (+) 0 sums a list, scanl (+) 0 creates a list of partial sums. Here, you probably want scanl1 (+), which doesn't add an extra zero at the beginning.

Prelude> scanl1 (+) [0, 2, 5, 9]
[0,2,7,16]
Sign up to request clarification or add additional context in comments.

Comments

5

I think being able to translate an imperative version of this code to functional style is a nice trick to have in the long run. Here is how I would solve this problem in one of those barbaric imperative languages:

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

Note that we have two variables here - the list of numbers and the rolling sum. When we convert this piece of code to functional style usually have to turn loops into (tail) recursion and variables into function arguments (since that is the only place they can "mutate").

accum_helper acc list

We can now try to work out the base case...

accum_helper acc [] = ...

...the recursive case

accum_helper acc (x:xs) = ...

...and finally use the parent function to do the variable initializing

accumulate xs = accum_helper 0 xs

Comments

3

Note that the fold functions can use an accumulator variable of any type -- even a tuple where one element is the cumulative sum and the second element is the list of previous cumulative sums.

Comments

3

Way less cool than hammar's answer, but another solution:

accumulate list = [sum $ take n list | n <- [1 .. length list]]

1 Comment

This doesn't work for infinite lists, while hammar's solution does.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.