Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a list by cumulatively adding elements of another list: Haskell

Tags:

haskell

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.

like image 296
Derek Meyer Avatar asked Nov 09 '11 00:11

Derek Meyer


People also ask

How does ++ work in Haskell?

The ++ operator is the list concatenation operator which takes two lists as operands and "combines" them into a single list. So if you have the list [x] and the list [y] then you can concatenate them like this: [x]++[y] to get [x, y ]. Notice that : takes an element and a list while ++ takes two lists.

How does cons work in Haskell?

Internally, Haskell lists are represented as linked cons-cells. A cons-cell is like a C struct with two pointer fields head and tail. The head field points to the first element of the list, the tail field to the rest of the list.

How do I print a list of elements in Haskell?

If show is ok to print your elements, you can use putStr ( unlines $ map show [(1,"A"),(2,"B"),(3,"C"),(4,"D")]) but you can replace show by any funtion that'll take your custom type and return a string.


1 Answers

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]
like image 88
hammar Avatar answered Sep 20 '22 06:09

hammar