(Background: The attempt to learn Haskell is very new to functional programming. Commonly used for Python.)
Suppose I have a list of 2-tuples, a histogram:
let h = [(1,2),(3,5),(4,6),(5,3),(6,7),(7,4),(8,6),(9,1)]
In mandatory terms, I want to change the second member of each pair as the sum of all the previous second pairs. In Python, this can do the following (admittedly, complex) list comprehension:
[(p[0], sum( [p[1] for p in histogram[:i+1]] )) for i, p in enumerate(histogram)]
Assuming the histogram refers to a list of 2 tuples, such as h above.
Here is what I still have in Haskell:
zip [fst p | p <- h] (scanl1 (+) [snd k | k <- h])
This works, but I wonder:
- Is it reading through a list once or twice?
- Could this be better expressed? (I expect so.)
If this is not clear, this is the expected result for the above:
[(1,2),(3,7),(4,13),(5,16),(6,23),(7,27),(8,33),(9,34)]